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
chore: remove unused components and dead code
rcourtman775ac5108c92
diff --git a/.opencode/config.json b/.opencode/config.jsondeleted file mode 100644index 308eceda98..0000000000--- a/.opencode/config.json+++ /dev/null@@ -1,24 +0,0 @@-{- "$schema": "https://opencode.ai/config.schema.json",- "agent": {- "tools": [- "pulse_*"- ]- },- "instructions": [- "You are Pulse's AI assistant for infrastructure monitoring and management.",- "You have access to pulse_* MCP tools. ALWAYS use them for infrastructure questions:",- "- pulse_get_infrastructure_state: Get all VMs, containers, hosts",- "- pulse_get_active_alerts: Get current alerts and warnings",- "- pulse_get_metrics_history: Get CPU/memory/disk history for resources",- "- pulse_get_resource_details: Get details for a specific VM/container",- "- pulse_get_baselines: Get learned normal behavior",- "- pulse_get_patterns: Get detected patterns and predictions",- "- pulse_get_disk_health: Get SMART data and disk status",- "- pulse_get_storage: Get storage pool information",- "- pulse_run_command: Execute commands on managed hosts",- "When asked about infrastructure, VMs, containers, alerts, metrics, or system status, ALWAYS use pulse_* tools.",- "Do NOT use webfetch for infrastructure questions - use the MCP tools.",- "Be concise and direct. Focus on actionable insights."- ]-}\ No newline at end of filediff --git a/frontend-modern/src/components/AI/GuestNotes.tsx b/frontend-modern/src/components/AI/GuestNotes.tsxdeleted file mode 100644index d9dc76295c..0000000000--- a/frontend-modern/src/components/AI/GuestNotes.tsx+++ /dev/null@@ -1,819 +0,0 @@-import { Component, createSignal, createEffect, For, Show, createMemo } from 'solid-js';-import { notificationStore } from '@/stores/notifications';-import { apiFetch } from '@/utils/apiClient';-import { logger } from '@/utils/logger';--interface Note {- id: string;- category: string;- title: string;- content: string;- created_at: string;- updated_at: string;-}--interface GuestKnowledge {- guest_id: string;- guest_name: string;- guest_type: string;- notes: Note[];- updated_at: string;-}--interface GuestNotesProps {- guestId: string;- guestName?: string;- guestType?: string;- customUrl?: string;- onCustomUrlUpdate?: (guestId: string, url: string) => void;-}--const CATEGORY_LABELS: Record<string, string> = {- service: 'Service',- path: 'Path',- config: 'Config',- credential: 'Credential',- learning: 'Learning',-};--const CATEGORY_ICONS: Record<string, string> = {- service: '⚙️',- path: '📁',- config: '📋',- credential: '🔐',- learning: '💡',-};--const CATEGORY_COLORS: Record<string, string> = {- service: 'bg-blue-500/20 border-blue-500/30 text-blue-300',- path: 'bg-amber-500/20 border-amber-500/30 text-amber-300',- config: 'bg-purple-500/20 border-purple-500/30 text-purple-300',- credential: 'bg-red-500/20 border-red-500/30 text-red-300',- learning: 'bg-green-500/20 border-green-500/30 text-green-300',-};--const CATEGORY_OPTIONS = ['service', 'path', 'config', 'credential', 'learning'];--// Quick templates for common note types-const TEMPLATES = [- { category: 'credential', title: 'Admin Password', placeholder: 'Enter admin password...' },- { category: 'credential', title: 'SSH Key', placeholder: 'Paste SSH private key or fingerprint...' },- { category: 'credential', title: 'API Key', placeholder: 'Enter API key...' },- { category: 'path', title: 'Config Directory', placeholder: '/path/to/config' },- { category: 'path', title: 'Data Directory', placeholder: '/path/to/data' },- { category: 'path', title: 'Log Location', placeholder: '/var/log/service.log' },- { category: 'service', title: 'Web Interface', placeholder: 'http://localhost:8080' },- { category: 'service', title: 'Database', placeholder: 'PostgreSQL on port 5432' },- { category: 'config', title: 'Port Number', placeholder: '8080' },- { category: 'config', title: 'Environment', placeholder: 'production' },-];--// Format relative time-const formatRelativeTime = (dateStr: string): string => {- const date = new Date(dateStr);- const now = new Date();- const diffMs = now.getTime() - date.getTime();- const diffMinutes = Math.floor(diffMs / 60000);- const diffHours = Math.floor(diffMs / 3600000);- const diffDays = Math.floor(diffMs / 86400000);-- if (diffMinutes < 1) return 'just now';- if (diffMinutes < 60) return `${diffMinutes}m ago`;- if (diffHours < 24) return `${diffHours}h ago`;- if (diffDays < 7) return `${diffDays}d ago`;- return date.toLocaleDateString();-};--export const GuestNotes: Component<GuestNotesProps> = (props) => {- const [knowledge, setKnowledge] = createSignal<GuestKnowledge | null>(null);- const [isLoading, setIsLoading] = createSignal(false);- const [isExpanded, setIsExpanded] = createSignal(false);- const [showAddForm, setShowAddForm] = createSignal(false);- const [showTemplates, setShowTemplates] = createSignal(false);- const [showActions, setShowActions] = createSignal(false);- const [editingNote, setEditingNote] = createSignal<Note | null>(null);- const [searchQuery, setSearchQuery] = createSignal('');- const [filterCategory, setFilterCategory] = createSignal<string>('');- const [showCredentials, setShowCredentials] = createSignal<Set<string>>(new Set());- const [deleteConfirmId, setDeleteConfirmId] = createSignal<string | null>(null);- const [clearConfirm, setClearConfirm] = createSignal(false);- const [isImporting, setIsImporting] = createSignal(false);-- // Form state- const [category, setCategory] = createSignal('learning');- const [title, setTitle] = createSignal('');- const [content, setContent] = createSignal('');-- // Guest URL state- const [guestUrl, setGuestUrl] = createSignal(props.customUrl || '');- const [isEditingUrl, setIsEditingUrl] = createSignal(false);- const [isSavingUrl, setIsSavingUrl] = createSignal(false);-- // Sync URL from props- createEffect(() => {- setGuestUrl(props.customUrl || '');- });-- // File input ref for import- let fileInputRef: HTMLInputElement | undefined;-- // Fetch knowledge when guestId changes- createEffect(() => {- const guestId = props.guestId;- if (guestId) {- loadKnowledge(guestId);- }- });-- const loadKnowledge = async (guestId: string) => {- setIsLoading(true);- try {- // Fetch knowledge and metadata in parallel- const [knowledgeResponse, metadataResponse] = await Promise.all([- apiFetch(`/api/ai/knowledge?guest_id=${encodeURIComponent(guestId)}`),- apiFetch(`/api/guests/metadata/${encodeURIComponent(guestId)}`),- ]);-- if (knowledgeResponse.ok) {- const data = await knowledgeResponse.json();- setKnowledge(data);- }-- // Load customUrl from metadata if not provided via props- if (metadataResponse.ok) {- const metadata = await metadataResponse.json();- if (metadata.customUrl && !props.customUrl) {- setGuestUrl(metadata.customUrl);- }- }- } catch (error) {- logger.error('Failed to load guest knowledge:', error);- } finally {- setIsLoading(false);- }- };-- const saveGuestUrl = async () => {- const url = guestUrl().trim();- setIsSavingUrl(true);- try {- const response = await apiFetch(`/api/guests/metadata/${encodeURIComponent(props.guestId)}`, {- method: 'PUT',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ customUrl: url }),- });- if (response.ok) {- notificationStore.success(url ? 'Guest URL saved' : 'Guest URL cleared');- setIsEditingUrl(false);- props.onCustomUrlUpdate?.(props.guestId, url);- } else {- notificationStore.error('Failed to save guest URL');- }- } catch (error) {- logger.error('Failed to save guest URL:', error);- notificationStore.error('Failed to save guest URL');- } finally {- setIsSavingUrl(false);- }- };-- const saveNote = async () => {- if (!title().trim() || !content().trim()) return;-- try {- const response = await apiFetch('/api/ai/knowledge/save', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- guest_id: props.guestId,- guest_name: props.guestName || props.guestId,- guest_type: props.guestType || 'unknown',- category: category(),- title: title().trim(),- content: content().trim(),- }),- });-- if (response.ok) {- notificationStore.success('Note saved');- // Reset form- setTitle('');- setContent('');- setShowAddForm(false);- setShowTemplates(false);- setEditingNote(null);- // Reload knowledge- loadKnowledge(props.guestId);- } else {- notificationStore.error('Failed to save note');- }- } catch (error) {- logger.error('Failed to save note:', error);- notificationStore.error('Failed to save note');- }- };-- const deleteNote = async (noteId: string) => {- try {- const response = await apiFetch('/api/ai/knowledge/delete', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- guest_id: props.guestId,- note_id: noteId,- }),- });-- if (response.ok) {- notificationStore.success('Note deleted');- setDeleteConfirmId(null);- loadKnowledge(props.guestId);- } else {- notificationStore.error('Failed to delete note');- }- } catch (error) {- logger.error('Failed to delete note:', error);- notificationStore.error('Failed to delete note');- }- };-- const exportNotes = async () => {- try {- const response = await apiFetch(`/api/ai/knowledge/export?guest_id=${encodeURIComponent(props.guestId)}`);- if (response.ok) {- const data = await response.json();- const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });- const url = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = url;- a.download = `pulse-notes-${props.guestName || props.guestId}.json`;- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- URL.revokeObjectURL(url);- notificationStore.success('Notes exported');- setShowActions(false);- } else {- notificationStore.error('Failed to export notes');- }- } catch (error) {- logger.error('Failed to export notes:', error);- notificationStore.error('Failed to export notes');- }- };-- const handleImportFile = async (event: Event) => {- const target = event.target as HTMLInputElement;- const file = target.files?.[0];- if (!file) return;-- setIsImporting(true);- try {- const text = await file.text();- const data = JSON.parse(text);-- // Add merge flag and ensure guest_id matches current- const importData = {- ...data,- guest_id: props.guestId,- guest_name: props.guestName || data.guest_name,- guest_type: props.guestType || data.guest_type,- merge: true, // Merge with existing notes- };-- const response = await apiFetch('/api/ai/knowledge/import', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(importData),- });-- if (response.ok) {- const result = await response.json();- notificationStore.success(`Imported ${result.imported} of ${result.total} notes`);- loadKnowledge(props.guestId);- setShowActions(false);- } else {- const errorText = await response.text();- notificationStore.error('Import failed: ' + errorText);- }- } catch (error) {- logger.error('Failed to import notes:', error);- notificationStore.error('Failed to parse import file');- } finally {- setIsImporting(false);- // Reset file input- if (fileInputRef) {- fileInputRef.value = '';- }- }- };-- const clearAllNotes = async () => {- try {- const response = await apiFetch('/api/ai/knowledge/clear', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- guest_id: props.guestId,- confirm: true,- }),- });-- if (response.ok) {- const result = await response.json();- notificationStore.success(`Cleared ${result.deleted} notes`);- setClearConfirm(false);- setShowActions(false);- loadKnowledge(props.guestId);- } else {- notificationStore.error('Failed to clear notes');- }- } catch (error) {- logger.error('Failed to clear notes:', error);- notificationStore.error('Failed to clear notes');- }- };-- const startEdit = (note: Note) => {- setEditingNote(note);- setCategory(note.category);- setTitle(note.title);- setContent(note.content);- setShowAddForm(true);- setShowTemplates(false);- };-- const useTemplate = (template: { category: string; title: string; placeholder: string }) => {- setCategory(template.category);- setTitle(template.title);- setContent('');- setShowTemplates(false);- setShowAddForm(true);- };-- const cancelEdit = () => {- setEditingNote(null);- setTitle('');- setContent('');- setShowAddForm(false);- setShowTemplates(false);- };-- const copyToClipboard = async (text: string, label: string) => {- try {- await navigator.clipboard.writeText(text);- notificationStore.success(`${label} copied to clipboard`);- } catch {- notificationStore.error('Failed to copy to clipboard');- }- };-- const toggleCredentialVisibility = (noteId: string) => {- const current = showCredentials();- const updated = new Set(current);- if (updated.has(noteId)) {- updated.delete(noteId);- } else {- updated.add(noteId);- }- setShowCredentials(updated);- };-- const maskCredential = (content: string): string => {- // Mask most of the content, showing only first 2 and last 2 chars- if (content.length <= 6) {- return '••••••';- }- return content.slice(0, 2) + '•'.repeat(Math.min(content.length - 4, 12)) + content.slice(-2);- };-- const notes = () => knowledge()?.notes || [];- const hasNotes = () => notes().length > 0;-- // Filtered notes based on search and category- const filteredNotes = createMemo(() => {- let result = notes();-- // Filter by category- const catFilter = filterCategory();- if (catFilter) {- result = result.filter(n => n.category === catFilter);- }-- // Filter by search query- const query = searchQuery().toLowerCase();- if (query) {- result = result.filter(n =>- n.title.toLowerCase().includes(query) ||- n.content.toLowerCase().includes(query) ||- CATEGORY_LABELS[n.category]?.toLowerCase().includes(query)- );- }-- // Sort by updated_at descending- return result.sort((a, b) =>- new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()- );- });-- // Group notes by category for summary- const notesByCategory = createMemo(() => {- const grouped: Record<string, number> = {};- for (const note of notes()) {- grouped[note.category] = (grouped[note.category] || 0) + 1;- }- return grouped;- });-- return (- <div class="border-t border-gray-700 pt-2 mt-2">- {/* Hidden file input for import */}- <input- ref={fileInputRef}- type="file"- accept=".json"- class="hidden"- onChange={handleImportFile}- />-- {/* Header with expand/collapse */}- <button- onClick={() => setIsExpanded(!isExpanded())}- class="flex items-center justify-between w-full text-left px-2 py-1 text-sm hover:bg-gray-700/50 rounded transition-colors"- >- <span class="flex items-center gap-2">- <svg class={`w-3 h-3 transition-transform ${isExpanded() ? 'rotate-90' : ''}`} fill="currentColor" viewBox="0 0 20 20">- <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />- </svg>- <span class="text-gray-300 font-medium">Saved Notes</span>- <Show when={hasNotes()}>- <span class="text-xs text-gray-500">({notes().length})</span>- </Show>- </span>- <Show when={isLoading()}>- <span class="text-xs text-gray-500">Loading...</span>- </Show>- </button>-- {/* Expandable content */}- <Show when={isExpanded()}>- <div class="mt-2 space-y-2 px-2">- {/* Guest URL field */}- <div class="bg-gray-800/50 rounded p-2 border border-gray-700">- <div class="flex items-center justify-between mb-1">- <span class="text-xs font-medium text-gray-400 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="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />- </svg>- Guest URL- </span>- <Show when={guestUrl() && !isEditingUrl()}>- <a- href={guestUrl()}- target="_blank"- rel="noopener noreferrer"- class="text-xs text-blue-400 hover:text-blue-300 flex items-center gap-1"- >- Open- <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="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />- </svg>- </a>- </Show>- </div>- <Show when={isEditingUrl()} fallback={- <div class="flex items-center gap-2">- <Show when={guestUrl()} fallback={- <span class="text-xs text-gray-500 italic">No URL set</span>- }>- <span class="text-xs text-gray-300 break-all font-mono">{guestUrl()}</span>- </Show>- <button- onClick={() => setIsEditingUrl(true)}- class="text-xs text-blue-400 hover:text-blue-300 ml-auto"- >- {guestUrl() ? 'Edit' : 'Add'}- </button>- </div>- }>- <div class="space-y-2">- <input- type="text"- value={guestUrl()}- onInput={(e) => setGuestUrl(e.target.value)}- onKeyDown={(e) => {- if (e.key === 'Enter') {- e.preventDefault();- saveGuestUrl();- } else if (e.key === 'Escape') {- e.preventDefault();- setGuestUrl(props.customUrl || '');- setIsEditingUrl(false);- }- }}- placeholder="https://192.168.1.100:8080"- class="w-full bg-gray-700 text-xs text-gray-200 rounded px-2 py-1.5 border border-gray-600 placeholder-gray-500 font-mono"- autofocus- />- <div class="flex gap-2 justify-end">- <button- onClick={() => {- setGuestUrl(props.customUrl || '');- setIsEditingUrl(false);- }}- class="text-xs px-2 py-1 text-gray-400 hover:text-gray-200"- >- Cancel- </button>- <button- onClick={saveGuestUrl}- disabled={isSavingUrl()}- class="text-xs px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-500 disabled:opacity-50"- >- {isSavingUrl() ? 'Saving...' : 'Save'}- </button>- </div>- </div>- </Show>- </div>-- {/* Search and filter bar - only show if there are notes */}- <Show when={hasNotes()}>- <div class="flex gap-2 mb-2">- <input- type="text"- placeholder="Search notes..."- value={searchQuery()}- onInput={(e) => setSearchQuery(e.target.value)}- class="flex-1 bg-gray-700 text-xs text-gray-200 rounded px-2 py-1 border border-gray-600 placeholder-gray-500"- />- <select- value={filterCategory()}- onChange={(e) => setFilterCategory(e.target.value)}- class="bg-gray-700 text-xs text-gray-200 rounded px-2 py-1 border border-gray-600"- >- <option value="">All</option>- <For each={CATEGORY_OPTIONS}>- {(cat) => (- <Show when={notesByCategory()[cat]}>- <option value={cat}>{CATEGORY_ICONS[cat]} {CATEGORY_LABELS[cat]} ({notesByCategory()[cat]})</option>- </Show>- )}- </For>- </select>- </div>- </Show>-- {/* Notes list */}- <Show when={hasNotes()} fallback={- <p class="text-xs text-gray-500 italic">No saved notes yet. Add notes to remember passwords, paths, and configs.</p>- }>- <Show when={filteredNotes().length > 0} fallback={- <p class="text-xs text-gray-500 italic">No notes match your search.</p>- }>- <div class="space-y-1.5 max-h-48 overflow-y-auto">- <For each={filteredNotes()}>- {(note) => (- <div class={`group rounded border px-2 py-1.5 text-xs ${CATEGORY_COLORS[note.category] || 'bg-gray-800/50 border-gray-700'}`}>- <div class="flex items-start justify-between gap-2">- <div class="flex-1 min-w-0">- <div class="flex items-center gap-1.5">- <span class="text-sm" title={CATEGORY_LABELS[note.category]}>{CATEGORY_ICONS[note.category]}</span>- <span class="text-gray-200 font-medium">{note.title}</span>- <span class="text-gray-500 text-[10px]" title={new Date(note.updated_at).toLocaleString()}>- {formatRelativeTime(note.updated_at)}- </span>- </div>- <div class="flex items-center gap-1 mt-0.5">- {/* Content - mask if credential and not revealed */}- <Show when={note.category === 'credential' && !showCredentials().has(note.id)}- fallback={- <p class="text-gray-300 break-words font-mono text-[11px]">{note.content}</p>- }>- <p class="text-gray-400 break-words font-mono text-[11px]">{maskCredential(note.content)}</p>- </Show>- </div>- </div>- <div class="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">- {/* Show/hide for credentials */}- <Show when={note.category === 'credential'}>- <button- onClick={() => toggleCredentialVisibility(note.id)}- class="text-gray-400 hover:text-yellow-400 p-0.5"- title={showCredentials().has(note.id) ? 'Hide' : 'Show'}- >- <Show when={showCredentials().has(note.id)} fallback={- <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 12a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>- }>- <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="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" /></svg>- </Show>- </button>- </Show>- {/* Copy button */}- <button- onClick={() => copyToClipboard(note.content, note.title)}- class="text-gray-400 hover:text-green-400 p-0.5"- title="Copy content"- >- <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 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" /></svg>- </button>- {/* Edit button */}- <button- onClick={() => startEdit(note)}- class="text-gray-400 hover:text-blue-400 p-0.5"- title="Edit"- >- <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="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>- {/* Delete button with confirmation */}- <Show when={deleteConfirmId() === note.id} fallback={- <button- onClick={() => setDeleteConfirmId(note.id)}- class="text-gray-400 hover:text-red-400 p-0.5"- title="Delete"- >- <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>- </button>- }>- <div class="flex items-center gap-1 bg-red-900/50 rounded px-1">- <span class="text-red-300 text-[10px]">Delete?</span>- <button- onClick={() => deleteNote(note.id)}- class="text-red-400 hover:text-red-300 p-0.5 font-bold"- title="Confirm delete"- >- ✓- </button>- <button- onClick={() => setDeleteConfirmId(null)}- class="text-gray-400 hover:text-gray-300 p-0.5"- title="Cancel"- >- ✗- </button>- </div>- </Show>- </div>- </div>- </div>- )}- </For>- </div>- </Show>- </Show>-- {/* Template picker */}- <Show when={showTemplates()}>- <div class="bg-gray-800/80 rounded p-2 border border-gray-700">- <div class="flex items-center justify-between mb-2">- <span class="text-xs font-medium text-gray-300">Quick Templates</span>- <button onClick={() => setShowTemplates(false)} class="text-gray-400 hover:text-gray-200 text-xs">✕</button>- </div>- <div class="grid grid-cols-2 gap-1">- <For each={TEMPLATES}>- {(template) => (- <button- onClick={() => useTemplate(template)}- class={`text-left px-2 py-1 rounded text-[10px] border ${CATEGORY_COLORS[template.category]} hover:opacity-80 transition-opacity`}- >- {CATEGORY_ICONS[template.category]} {template.title}- </button>- )}- </For>- </div>- </div>- </Show>-- {/* Actions menu (Export/Import/Clear) */}- <Show when={showActions()}>- <div class="bg-gray-800/80 rounded p-2 border border-gray-700 space-y-1">- <div class="flex items-center justify-between mb-1">- <span class="text-xs font-medium text-gray-300">Actions</span>- <button onClick={() => { setShowActions(false); setClearConfirm(false); }} class="text-gray-400 hover:text-gray-200 text-xs">✕</button>- </div>- <button- onClick={exportNotes}- disabled={!hasNotes()}- class="w-full text-left px-2 py-1.5 rounded text-xs bg-blue-600/20 hover:bg-blue-600/30 text-blue-300 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"- >- <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="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>- Export Notes (JSON)- </button>- <button- onClick={() => fileInputRef?.click()}- disabled={isImporting()}- class="w-full text-left px-2 py-1.5 rounded text-xs bg-green-600/20 hover:bg-green-600/30 text-green-300 disabled:opacity-50 flex items-center gap-2"- >- <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" /></svg>- {isImporting() ? 'Importing...' : 'Import Notes (Merge)'}- </button>- <Show when={clearConfirm()} fallback={- <button- onClick={() => setClearConfirm(true)}- disabled={!hasNotes()}- class="w-full text-left px-2 py-1.5 rounded text-xs bg-red-600/20 hover:bg-red-600/30 text-red-300 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"- >- <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>- Clear All Notes- </button>- }>- <div class="bg-red-900/50 rounded p-2 flex items-center justify-between">- <span class="text-red-300 text-[10px]">Delete all {notes().length} notes?</span>- <div class="flex gap-1">- <button onClick={clearAllNotes} class="px-2 py-0.5 bg-red-600 hover:bg-red-500 text-white rounded text-[10px]">Yes, clear all</button>- <button onClick={() => setClearConfirm(false)} class="px-2 py-0.5 bg-gray-600 hover:bg-gray-500 text-white rounded text-[10px]">Cancel</button>- </div>- </div>- </Show>- </div>- </Show>-- {/* Add/Edit form */}- <Show when={showAddForm()}>- <div class="bg-gray-800/80 rounded p-2 space-y-2 border border-gray-700">- <div class="flex items-center justify-between mb-1">- <span class="text-xs font-medium text-gray-300">- {editingNote() ? 'Edit Note' : 'Add Note'}- </span>- <Show when={editingNote()}>- <span class="text-[10px] text-gray-500">ID: {editingNote()?.id}</span>- </Show>- </div>- <div class="flex gap-2">- <select- value={category()}- onChange={(e) => setCategory(e.target.value)}- class="bg-gray-700 text-xs text-gray-200 rounded px-2 py-1.5 border border-gray-600"- >- <For each={CATEGORY_OPTIONS}>- {(cat) => <option value={cat}>{CATEGORY_ICONS[cat]} {CATEGORY_LABELS[cat]}</option>}- </For>- </select>- <input- type="text"- placeholder="Title (e.g., 'Admin Password')"- value={title()}- onInput={(e) => setTitle(e.target.value)}- class="flex-1 bg-gray-700 text-xs text-gray-200 rounded px-2 py-1.5 border border-gray-600 placeholder-gray-500"- />- </div>- <textarea- placeholder={category() === 'credential'- ? "Enter credential value (stored encrypted)..."- : "Content..."}- value={content()}- onInput={(e) => setContent(e.target.value)}- class="w-full bg-gray-700 text-xs text-gray-200 rounded px-2 py-1.5 border border-gray-600 resize-none placeholder-gray-500 font-mono"- rows={2}- />- <Show when={category() === 'credential'}>- <p class="text-[10px] text-amber-400 flex items-center gap-1">- <span>🔐</span> Credentials are encrypted at rest and masked in the UI- </p>- </Show>- <div class="flex gap-2 justify-end">- <button- onClick={cancelEdit}- class="text-xs px-2 py-1 text-gray-400 hover:text-gray-200"- >- Cancel- </button>- <button- onClick={saveNote}- disabled={!title().trim() || !content().trim()}- class="text-xs px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"- >- {editingNote() ? 'Update' : 'Save'}- </button>- </div>- </div>- </Show>-- {/* Action buttons row */}- <Show when={!showAddForm() && !showTemplates() && !showActions()}>- <div class="flex items-center gap-2 pt-1">- <button- onClick={() => setShowAddForm(true)}- class="text-xs text-blue-400 hover:text-blue-300 flex items-center gap-1"- >- <span>+</span> Add note- </button>- <button- onClick={() => setShowTemplates(true)}- class="text-xs text-purple-400 hover:text-purple-300 flex items-center gap-1"- >- <span>📝</span> Templates- </button>- <button- onClick={() => setShowActions(true)}- class="text-xs text-gray-400 hover:text-gray-300 flex items-center gap-1"- >- <span>⚙️</span> Actions- </button>- </div>- </Show>- </div>- </Show>- </div>- );-};diff --git a/frontend-modern/src/components/Dashboard/AnomalyCell.tsx b/frontend-modern/src/components/Dashboard/AnomalyCell.tsxdeleted file mode 100644index 03a214de88..0000000000--- a/frontend-modern/src/components/Dashboard/AnomalyCell.tsx+++ /dev/null@@ -1,129 +0,0 @@-import { Show, createMemo, For } from 'solid-js';-import type { AnomalyReport, AnomalySeverity } from '@/types/aiIntelligence';--interface AnomalyCellProps {- anomalies: AnomalyReport[];-}--// Severity priority for sorting (higher = more severe)-const severityPriority: Record<AnomalySeverity, number> = {- critical: 4,- high: 3,- medium: 2,- low: 1,-};--// Config for each severity level-const severityConfig: Record<AnomalySeverity, { bg: string; text: string; border: string }> = {- critical: {- bg: 'bg-red-100 dark:bg-red-900/40',- text: 'text-red-700 dark:text-red-300',- border: 'border-red-300 dark:border-red-700',- },- high: {- bg: 'bg-orange-100 dark:bg-orange-900/40',- text: 'text-orange-700 dark:text-orange-300',- border: 'border-orange-300 dark:border-orange-700',- },- medium: {- bg: 'bg-yellow-100 dark:bg-yellow-900/40',- text: 'text-yellow-700 dark:text-yellow-300',- border: 'border-yellow-300 dark:border-yellow-700',- },- low: {- bg: 'bg-blue-100 dark:bg-blue-900/40',- text: 'text-blue-700 dark:text-blue-300',- border: 'border-blue-300 dark:border-blue-700',- },-};--/**- * Cell component that displays anomaly indicators for a guest.- * Shows metric badges with severity colors and deviation info.- */-export function AnomalyCell(props: AnomalyCellProps) {- // Sort by severity (most severe first)- const sortedAnomalies = createMemo(() =>- [...props.anomalies].sort(- (a, b) => severityPriority[b.severity] - severityPriority[a.severity]- )- );-- // Format ratio for display- const formatRatio = (anomaly: AnomalyReport): string => {- if (anomaly.baseline_mean === 0) return '↑';- const ratio = anomaly.current_value / anomaly.baseline_mean;- if (ratio >= 2) return `${ratio.toFixed(1)}x`;- if (ratio >= 1.5) return '↑↑';- if (ratio > 1) return '↑';- if (ratio <= 0.5) return '↓↓';- return '↓';- };-- // Metric labels- const metricLabels: Record<string, string> = {- cpu: 'CPU',- memory: 'MEM',- disk: 'DSK',- };-- return (- <Show when={props.anomalies.length > 0}>- <div class="flex items-center gap-0.5 flex-wrap justify-center">- <For each={sortedAnomalies().slice(0, 3)}>- {(anomaly) => {- const config = severityConfig[anomaly.severity];- return (- <span- class={`inline-flex items-center px-1 py-0.5 rounded text-[8px] font-bold ${config.bg} ${config.text} border ${config.border}`}- title={anomaly.description}- >- <span>{metricLabels[anomaly.metric] || anomaly.metric.toUpperCase()}</span>- <span class="ml-0.5 opacity-75">{formatRatio(anomaly)}</span>- </span>- );- }}- </For>- <Show when={sortedAnomalies().length > 3}>- <span- class="text-[8px] text-gray-500 dark:text-gray-400"- title={`${sortedAnomalies().length - 3} more anomalies`}- >- +{sortedAnomalies().length - 3}- </span>- </Show>- </div>- </Show>- );-}--/**- * Small dot indicator showing if a guest has any anomalies.- * Used for compact views where space is limited.- */-export function AnomalyDot(props: { hasAnomalies: boolean; severity?: AnomalySeverity; title?: string }) {- const dotColor = createMemo(() => {- if (!props.hasAnomalies) return '';- switch (props.severity) {- case 'critical':- return 'bg-red-500';- case 'high':- return 'bg-orange-500';- case 'medium':- return 'bg-yellow-500';- case 'low':- return 'bg-blue-400';- default:- return 'bg-gray-400';- }- });-- return (- <Show when={props.hasAnomalies}>- <span- class={`inline-block w-1.5 h-1.5 rounded-full ${dotColor()} animate-pulse`}- title={props.title || 'Baseline anomaly detected'}- />- </Show>- );-}diff --git a/frontend-modern/src/components/Dashboard/AnomalyIndicator.tsx b/frontend-modern/src/components/Dashboard/AnomalyIndicator.tsxdeleted file mode 100644index 569f3810f1..0000000000--- a/frontend-modern/src/components/Dashboard/AnomalyIndicator.tsx+++ /dev/null@@ -1,125 +0,0 @@-import { Show, createMemo } from 'solid-js';-import type { AnomalyReport, AnomalySeverity } from '@/types/aiIntelligence';--interface AnomalyIndicatorProps {- anomaly: AnomalyReport | null;- compact?: boolean; // Only show icon, no text-}--/**- * Displays an anomaly indicator badge for a metric.- * Shows severity level and how much above/below baseline the current value is.- */-export function AnomalyIndicator(props: AnomalyIndicatorProps) {- const severityConfig = createMemo(() => {- if (!props.anomaly) return null;-- const configs: Record<AnomalySeverity, { bg: string; text: string; icon: string }> = {- critical: {- bg: 'bg-red-500',- text: 'text-white',- icon: '🔴',- },- high: {- bg: 'bg-orange-500',- text: 'text-white',- icon: '🟠',- },- medium: {- bg: 'bg-yellow-500',- text: 'text-gray-800',- icon: '🟡',- },- low: {- bg: 'bg-blue-400',- text: 'text-white',- icon: '🔵',- },- };-- return configs[props.anomaly.severity] || configs.medium;- });-- // Calculate how many times above baseline- const multiplier = createMemo(() => {- if (!props.anomaly || props.anomaly.baseline_mean === 0) return null;- const ratio = props.anomaly.current_value / props.anomaly.baseline_mean;- if (ratio >= 2) {- return `${ratio.toFixed(1)}x`;- }- return null;- });-- // Simplified label for compact display- const compactLabel = createMemo(() => {- const m = multiplier();- if (m) return m;- if (props.anomaly) {- const zAbs = Math.abs(props.anomaly.z_score);- if (zAbs >= 4) return 'CRIT';- if (zAbs >= 3) return 'HIGH';- if (zAbs >= 2.5) return 'MED';- return 'LOW';- }- return '';- });-- return (- <Show when={props.anomaly && severityConfig()}>- <div- class={`inline-flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] font-bold ${severityConfig()!.bg- } ${severityConfig()!.text} animate-pulse`}- title={props.anomaly!.description}- >- <Show when={!props.compact}>- <span>{severityConfig()!.icon}</span>- </Show>- <span>{compactLabel()}</span>- </div>- </Show>- );-}--/**- * Small inline indicator for use within metric bars.- * Just shows an icon and optionally the multiplier.- */-export function AnomalyBadge(props: { anomaly: AnomalyReport | null }) {- const multiplier = createMemo(() => {- if (!props.anomaly || props.anomaly.baseline_mean === 0) return null;- const ratio = props.anomaly.current_value / props.anomaly.baseline_mean;- if (ratio >= 1.5) {- return `${ratio.toFixed(1)}x`;- }- return null;- });-- const severityColor = createMemo(() => {- if (!props.anomaly) return '';- switch (props.anomaly.severity) {- case 'critical':- return 'text-red-400';- case 'high':- return 'text-orange-400';- case 'medium':- return 'text-yellow-400';- case 'low':- return 'text-blue-400';- default:- return 'text-gray-400';- }- });-- return (- <Show when={props.anomaly}>- <span- class={`ml-1 ${severityColor()} font-bold text-[9px] animate-pulse`}- title={props.anomaly!.description}- >- <Show when={multiplier()} fallback="⚠">- {multiplier()}↑- </Show>- </span>- </Show>- );-}diff --git a/frontend-modern/src/components/Dashboard/IOMetric.tsx b/frontend-modern/src/components/Dashboard/IOMetric.tsxdeleted file mode 100644index 431711fb4e..0000000000--- a/frontend-modern/src/components/Dashboard/IOMetric.tsx+++ /dev/null@@ -1,48 +0,0 @@-import { createMemo, Show, createEffect, createSignal } from 'solid-js';-import { formatSpeed } from '@/utils/format';--interface IOMetricProps {- value: (() => number) | number;- disabled?: boolean;-}--export function IOMetric(props: IOMetricProps) {- // Handle both accessor functions and direct values- const getValue = () => {- return typeof props.value === 'function' ? props.value() : props.value;- };-- // Create a local signal that tracks the value- const [currentValue, setCurrentValue] = createSignal(getValue() || 0);-- // Update the signal when value changes- createEffect(() => {- const newValue = getValue() || 0;- const oldValue = currentValue();- if (newValue !== oldValue) {- setCurrentValue(newValue);- }- });-- // Color based on speed (MB/s) - uses color intensity to indicate activity level- const colorClass = createMemo(() => {- if (props.disabled) return 'text-gray-400 dark:text-gray-500';-- const mbps = currentValue() / (1024 * 1024);- if (mbps < 1) return 'text-gray-500 dark:text-gray-400';- if (mbps < 10) return 'text-green-600 dark:text-green-400';- if (mbps < 50) return 'text-yellow-600 dark:text-yellow-400';- return 'text-red-600 dark:text-red-400';- });-- return (- <Show- when={!props.disabled}- fallback={<div class="min-h-[24px] flex items-center text-xs text-gray-400">-</div>}- >- <div class={`min-h-[24px] text-xs ${colorClass()} flex items-center`}>- {formatSpeed(currentValue(), 0)}- </div>- </Show>- );-}diff --git a/frontend-modern/src/components/Docker/StackedContainerBar.tsx b/frontend-modern/src/components/Docker/StackedContainerBar.tsxdeleted file mode 100644index fbedf3a67f..0000000000--- a/frontend-modern/src/components/Docker/StackedContainerBar.tsx+++ /dev/null@@ -1,115 +0,0 @@-import { Show, For, createMemo, createSignal } from 'solid-js';-import { Portal } from 'solid-js/web';--interface StackedContainerBarProps {- running: number;- stopped: number;- error: number;- total: number;-}--// Colors for container states-const STATE_COLORS = {- running: 'rgba(34, 197, 94, 0.6)', // green- stopped: 'rgba(156, 163, 175, 0.6)', // gray- error: 'rgba(239, 68, 68, 0.6)', // red-};--export function StackedContainerBar(props: StackedContainerBarProps) {- const [showTooltip, setShowTooltip] = createSignal(false);- const [tooltipPos, setTooltipPos] = createSignal({ x: 0, y: 0 });- let containerRef: HTMLDivElement | undefined;-- // Calculate segments- const segments = createMemo(() => {- if (props.total <= 0) return [];-- const runningPercent = (props.running / props.total) * 100;- const stoppedPercent = (props.stopped / props.total) * 100;- const errorPercent = (props.error / props.total) * 100;-- return [- { type: 'Running', count: props.running, percent: runningPercent, color: STATE_COLORS.running },- { type: 'Stopped', count: props.stopped, percent: stoppedPercent, color: STATE_COLORS.stopped },- { type: 'Error', count: props.error, percent: errorPercent, color: STATE_COLORS.error },- ].filter(s => s.count > 0);- });-- const handleMouseEnter = (e: MouseEvent) => {- const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();- setTooltipPos({ x: rect.left + rect.width / 2, y: rect.top });- setShowTooltip(true);- };-- const handleMouseLeave = () => {- setShowTooltip(false);- };-- return (- <div ref={containerRef} class="metric-text w-full h-4 flex items-center justify-center">- <div- class="relative w-full h-full overflow-hidden bg-gray-200 dark:bg-gray-600 rounded"- onMouseEnter={handleMouseEnter}- onMouseLeave={handleMouseLeave}- >- {/* Stacked segments */}- <div class="absolute top-0 left-0 h-full w-full flex">- <For each={segments()}>- {(segment, idx) => (- <div- class="h-full transition-all duration-300"- style={{- width: `${segment.percent}%`,- 'background-color': segment.color,- 'border-right': idx() < segments().length - 1 ? '1px solid rgba(255,255,255,0.3)' : 'none',- }}- />- )}- </For>- </div>-- {/* Label overlay */}- <span class="absolute inset-0 flex items-center justify-center text-[10px] font-semibold text-gray-700 dark:text-gray-100 leading-none pointer-events-none">- <span class="flex items-center gap-1 whitespace-nowrap px-0.5">- <span>{props.running}/{props.total}</span>- </span>- </span>- </div>-- {/* Tooltip */}- <Show when={showTooltip()}>- <Portal mount={document.body}>- <div- class="fixed z-[9999] pointer-events-none"- style={{- left: `${tooltipPos().x}px`,- top: `${tooltipPos().y - 8}px`,- transform: 'translate(-50%, -100%)',- }}- >- <div class="bg-gray-900 dark:bg-gray-800 text-white text-[10px] rounded-md shadow-lg px-2 py-1.5 min-w-[120px] border border-gray-700">- <div class="font-medium mb-1 text-gray-300 border-b border-gray-700 pb-1">- Container Status- </div>- <For each={segments()}>- {(item, idx) => (- <div class="flex justify-between gap-3 py-0.5" classList={{ 'border-t border-gray-700/50': idx() > 0 }}>- <span- class="truncate"- style={{ color: item.color.replace('0.6)', '1)') }}- >- {item.type}- </span>- <span class="whitespace-nowrap text-gray-300">- {item.count}- </span>- </div>- )}- </For>- </div>- </div>- </Portal>- </Show>- </div>- );-}diff --git a/frontend-modern/src/components/shared/AIImpactTimelinePanel.tsx b/frontend-modern/src/components/shared/AIImpactTimelinePanel.tsxdeleted file mode 100644index 153cfed5cb..0000000000--- a/frontend-modern/src/components/shared/AIImpactTimelinePanel.tsx+++ /dev/null@@ -1,201 +0,0 @@-import { Component, createEffect, createSignal, For, Show } from 'solid-js';-import { AIAPI } from '@/api/ai';-import { logger } from '@/utils/logger';-import type { RemediationRecord, RemediationStats } from '@/types/aiIntelligence';--const DEFAULT_UPGRADE_URL = 'https://pulserelay.pro/';--export const AIImpactTimelinePanel: Component<{ hours?: number; showWhenEmpty?: boolean }> = (props) => {- const [remediations, setRemediations] = createSignal<RemediationRecord[]>([]);- const [stats, setStats] = createSignal<RemediationStats | null>(null);- const [loading, setLoading] = createSignal(false);- const [locked, setLocked] = createSignal(false);- const [upgradeUrl, setUpgradeUrl] = createSignal(DEFAULT_UPGRADE_URL);- const [error, setError] = createSignal('');- const showWhenEmpty = () => Boolean(props.showWhenEmpty);- const hours = () => props.hours ?? 168;-- const loadData = async () => {- setLoading(true);- setError('');- try {- const response = await AIAPI.getRemediations({ hours: hours(), limit: 6 });- setLocked(Boolean(response.license_required));- setUpgradeUrl(response.upgrade_url || DEFAULT_UPGRADE_URL);- setStats(response.stats || null);- setRemediations(response.remediations || []);- } catch (e) {- logger.error('Failed to load AI impact timeline:', e);- setError('Failed to load AI impact timeline.');- } finally {- setLoading(false);- }- };-- createEffect(() => {- void loadData();- });-- const shouldShow = () => showWhenEmpty() || loading() || remediations().length > 0 || (stats()?.total || 0) > 0;-- const formatRelativeTime = (ts: string) => {- const date = new Date(ts);- 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`;- if (diffDays < 7) return `${diffDays}d ago`;- return date.toLocaleDateString();- };-- const outcomeBadge = (outcome: string) => {- const styles: Record<string, string> = {- resolved: 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300',- partial: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',- failed: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',- };- return styles[outcome] || 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300';- };-- const truncateText = (text: string, limit: number) => {- if (text.length <= limit) return text;- return `${text.slice(0, limit - 3)}...`;- };-- const statValue = (key: keyof RemediationStats) => stats()?.[key] ?? 0;-- return (- <Show when={shouldShow()}>- <div class="bg-gradient-to-r from-emerald-50 to-sky-50 dark:from-emerald-900/20 dark:to-sky-900/20 border border-emerald-200 dark:border-emerald-700 rounded-lg overflow-hidden">- <div class="px-4 py-3 flex items-center justify-between border-b border-emerald-200/70 dark:border-emerald-700/70">- <div class="flex items-center gap-2">- <svg class="w-5 h-5 text-emerald-600 dark:text-emerald-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="font-medium text-emerald-900 dark:text-emerald-100">Pulse AI Impact</span>- <Show when={locked()}>- <span class="px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 rounded-full">- Locked- </span>- </Show>- </div>- <span class="text-xs text-emerald-600 dark:text-emerald-300">{Math.round(hours() / 24)} days</span>- </div>- <div class="px-4 pb-4 space-y-3">- <Show when={loading()}>- <div class="text-sm text-emerald-700 dark:text-emerald-200 flex items-center gap-2">- <span class="h-4 w-4 border-2 border-current border-t-transparent rounded-full animate-spin" />- Loading impact...- </div>- </Show>-- <Show when={error() && !loading()}>- <div class="text-sm text-red-600 dark:text-red-400">- {error()}- </div>- </Show>-- <Show when={stats() && !loading()}>- <div class="grid grid-cols-2 gap-2 text-xs">- <div class="rounded-lg bg-white/70 dark:bg-gray-900/40 border border-emerald-100 dark:border-emerald-800 px-2 py-1">- <span class="text-emerald-600 dark:text-emerald-300">Resolved</span>- <span class="ml-1 font-semibold text-emerald-900 dark:text-emerald-100">{statValue('resolved')}</span>- </div>- <div class="rounded-lg bg-white/70 dark:bg-gray-900/40 border border-emerald-100 dark:border-emerald-800 px-2 py-1">- <span class="text-emerald-600 dark:text-emerald-300">Auto-fix</span>- <span class="ml-1 font-semibold text-emerald-900 dark:text-emerald-100">{statValue('automatic')}</span>- </div>- <div class="rounded-lg bg-white/70 dark:bg-gray-900/40 border border-emerald-100 dark:border-emerald-800 px-2 py-1">- <span class="text-emerald-600 dark:text-emerald-300">Partial</span>- <span class="ml-1 font-semibold text-emerald-900 dark:text-emerald-100">{statValue('partial')}</span>- </div>- <div class="rounded-lg bg-white/70 dark:bg-gray-900/40 border border-emerald-100 dark:border-emerald-800 px-2 py-1">- <span class="text-emerald-600 dark:text-emerald-300">Failed</span>- <span class="ml-1 font-semibold text-emerald-900 dark:text-emerald-100">{statValue('failed')}</span>- </div>- </div>- </Show>-- <Show when={locked() && !loading()}>- <div class="rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 p-3 text-sm text-amber-800 dark:text-amber-200">- <div class="flex items-center justify-between gap-3">- <div>- <p class="font-medium">Pulse Pro required</p>- <p class="text-xs text-amber-700 dark:text-amber-300 mt-1">- Pulse AI has handled {statValue('resolved')} remediations in the last {Math.round(hours() / 24)} days. Upgrade to view the receipts.- </p>- </div>- <a- class="text-xs font-medium text-amber-800 dark:text-amber-200 underline"- href={upgradeUrl()}- target="_blank"- rel="noreferrer"- >- Upgrade- </a>- </div>- </div>- </Show>-- <Show when={!locked() && !loading()}>- <Show- when={remediations().length > 0}- fallback={- <p class="text-sm text-emerald-700 dark:text-emerald-200 text-center py-2">- No remediations logged yet. Pulse AI will highlight fixes here as they happen.- </p>- }- >- <div class="space-y-2">- <For each={remediations()}>- {(rec) => (- <div class="bg-white/70 dark:bg-gray-900/40 border border-emerald-100 dark:border-emerald-800 rounded-lg p-3">- <div class="flex items-start justify-between gap-2">- <div class="flex-1">- <div class="flex items-center gap-2 flex-wrap">- <span class={`px-2 py-0.5 text-[10px] font-semibold rounded-full ${outcomeBadge(rec.outcome)}`}>- {rec.outcome}- </span>- <Show when={rec.automatic}>- <span class="px-2 py-0.5 text-[10px] font-semibold rounded-full bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300">- Auto-Fix- </span>- </Show>- <span class="text-xs font-medium text-emerald-900 dark:text-emerald-100">- {rec.action}- </span>- </div>- <p class="text-xs text-emerald-700 dark:text-emerald-200 mt-1">- {rec.problem}- </p>- <Show when={rec.note}>- <p class="text-[11px] text-emerald-600 dark:text-emerald-300 mt-1">- {rec.note}- </p>- </Show>- <Show when={rec.output}>- <p class="text-[11px] text-emerald-600 dark:text-emerald-300 mt-1">- Evidence: {truncateText(rec.output || '', 140)}- </p>- </Show>- </div>- <span class="text-[11px] text-emerald-600 dark:text-emerald-300 whitespace-nowrap">- {formatRelativeTime(rec.timestamp)}- </span>- </div>- </div>- )}- </For>- </div>- </Show>- </Show>- </div>- </div>- </Show>- );-};diff --git a/frontend-modern/src/components/shared/AIInsightsPanel.tsx b/frontend-modern/src/components/shared/AIInsightsPanel.tsxdeleted file mode 100644index 22f4e63d95..0000000000--- a/frontend-modern/src/components/shared/AIInsightsPanel.tsx+++ /dev/null@@ -1,263 +0,0 @@-import { Component, createSignal, createEffect, Show, For } from 'solid-js';-import { AIAPI } from '@/api/ai';-import { logger } from '@/utils/logger';-import type { FailurePrediction, ResourceCorrelation } from '@/types/aiIntelligence';--/**- * AIInsightsPanel displays AI-learned predictions and correlations- * Shows failure predictions with confidence levels and resource dependencies- */-export const AIInsightsPanel: Component<{ resourceId?: string; showWhenEmpty?: boolean }> = (props) => {- const [predictions, setPredictions] = createSignal<FailurePrediction[]>([]);- const [correlations, setCorrelations] = createSignal<ResourceCorrelation[]>([]);- const [loading, setLoading] = createSignal(false);- const [expanded, setExpanded] = createSignal(false);- const [locked, setLocked] = createSignal(false);- const [lockedCount, setLockedCount] = createSignal(0);- const [upgradeUrl, setUpgradeUrl] = createSignal('https://pulserelay.pro/');- const [error, setError] = createSignal('');- const showWhenEmpty = () => Boolean(props.showWhenEmpty);-- const loadData = async () => {- setLoading(true);- setError('');- try {- const [predResp, corrResp] = await Promise.all([- AIAPI.getPredictions(props.resourceId),- AIAPI.getCorrelations(props.resourceId),- ]);- const licenseLocked = Boolean(predResp.license_required || corrResp.license_required);- setLocked(licenseLocked);- setUpgradeUrl(predResp.upgrade_url || corrResp.upgrade_url || 'https://pulserelay.pro/');- if (licenseLocked) {- const predCount = predResp.count || 0;- const corrCount = corrResp.count || 0;- setLockedCount(predCount + corrCount);- setPredictions([]);- setCorrelations([]);- } else {- setLockedCount(0);- setPredictions(predResp.predictions || []);- setCorrelations(corrResp.correlations || []);- }- } catch (e) {- logger.error('Failed to load AI insights:', e);- setError('Failed to load AI insights.');- } finally {- setLoading(false);- }- };-- createEffect(() => {- loadData();- });-- const totalInsights = () => predictions().length + correlations().length;- const displayedCount = () => (locked() ? lockedCount() : totalInsights());- const shouldShow = () => showWhenEmpty() || loading() || displayedCount() > 0;-- // Format days until in a human-readable way- const formatDaysUntil = (days: number) => {- if (days < 0) return 'Overdue';- if (days < 1) return 'Today';- if (days < 2) return 'Tomorrow';- return `In ${Math.round(days)} days`;- };-- // Get severity color based on days until and confidence- const getPredictionColor = (pred: FailurePrediction) => {- if (pred.is_overdue || pred.days_until < 0) return 'text-red-600 dark:text-red-400';- if (pred.days_until < 3) return 'text-amber-600 dark:text-amber-400';- if (pred.days_until < 7) return 'text-yellow-600 dark:text-yellow-400';- return 'text-blue-600 dark:text-blue-400';- };-- // Get event type display name- const getEventDisplayName = (eventType: string) => {- const names: Record<string, string> = {- high_memory: 'High Memory',- high_cpu: 'High CPU',- disk_full: 'Disk Full',- oom: 'Out of Memory',- restart: 'Restart',- unresponsive: 'Unresponsive',- backup_failed: 'Backup Failure',- };- if (names[eventType]) {- return names[eventType];- }- return eventType- .split(/[_-]/)- .map((part) => {- if (part === 'cpu') return 'CPU';- if (part === 'vm') return 'VM';- if (part === 'pbs') return 'PBS';- if (part === 'raid') return 'RAID';- return part.charAt(0).toUpperCase() + part.slice(1);- })- .join(' ');- };-- return (- <Show when={shouldShow()}>- <div class="bg-gradient-to-r from-purple-50 to-indigo-50 dark:from-purple-900/20 dark:to-indigo-900/20 border border-purple-200 dark:border-purple-700 rounded-lg overflow-hidden">- {/* Header */}- <button- type="button"- onClick={() => setExpanded(!expanded())}- class="w-full px-4 py-3 flex items-center justify-between hover:bg-purple-100/50 dark:hover:bg-purple-800/30 transition-colors"- >- <div class="flex items-center gap-2">- <svg class="w-5 h-5 text-purple-600 dark:text-purple-400" 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>- <span class="font-medium text-purple-900 dark:text-purple-100">- Pulse Insights- </span>- <Show when={displayedCount() > 0}>- <span class="px-2 py-0.5 text-xs font-medium bg-purple-200 dark:bg-purple-700 text-purple-800 dark:text-purple-200 rounded-full">- {displayedCount()}- </span>- </Show>- <Show when={locked()}>- <span class="px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 rounded-full">- Locked- </span>- </Show>- </div>- <svg- class={`w-5 h-5 text-purple-600 dark:text-purple-400 transition-transform ${expanded() ? '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>-- {/* Content */}- <Show when={expanded()}>- <div class="px-4 pb-4 space-y-4">- {/* Loading state */}- <Show when={loading()}>- <div class="text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2">- <span class="h-4 w-4 border-2 border-current border-t-transparent rounded-full animate-spin" />- Loading insights...- </div>- </Show>-- <Show when={error() && !loading()}>- <div class="text-sm text-red-600 dark:text-red-400">- {error()}- </div>- </Show>-- <Show when={locked() && !loading()}>- <div class="rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 p-3 text-sm text-amber-800 dark:text-amber-200">- <div class="flex items-center justify-between gap-3">- <div>- <p class="font-medium">Pulse Pro required</p>- <p class="text-xs text-amber-700 dark:text-amber-300 mt-1">- Predictive intelligence is available with Pulse Pro. {lockedCount() || 0} insights are ready to review.- </p>- </div>- <a- class="text-xs font-medium text-amber-800 dark:text-amber-200 underline"- href={upgradeUrl()}- target="_blank"- rel="noreferrer"- >- Upgrade- </a>- </div>- </div>- </Show>-- {/* Predictions */}- <Show when={!locked() && predictions().length > 0}>- <div>- <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-1">- <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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />- </svg>- Failure Predictions- </h4>- <div class="space-y-2">- <For each={predictions()}>- {(pred) => (- <div class="bg-white/50 dark:bg-gray-800/50 rounded-lg p-3 border border-purple-100 dark:border-purple-800">- <div class="flex items-start justify-between gap-2">- <div class="flex-1">- <div class={`font-medium ${getPredictionColor(pred)}`}>- {getEventDisplayName(pred.event_type)}- <span class="ml-2 text-sm font-normal">- {formatDaysUntil(pred.days_until)}- </span>- </div>- <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">- {pred.basis}- </p>- </div>- <div class="text-right shrink-0">- <div class="text-xs text-gray-500 dark:text-gray-400">- {Math.round(pred.confidence * 100)}% confidence- </div>- </div>- </div>- </div>- )}- </For>- </div>- </div>- </Show>-- {/* Correlations */}- <Show when={!locked() && correlations().length > 0}>- <div>- <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-1">- <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="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />- </svg>- Resource Dependencies- </h4>- <div class="space-y-2">- <For each={correlations()}>- {(corr) => (- <div class="bg-white/50 dark:bg-gray-800/50 rounded-lg p-3 border border-purple-100 dark:border-purple-800">- <div class="flex items-center gap-2 text-sm">- <span class="font-medium text-gray-800 dark:text-gray-200">- {corr.source_name || corr.source_id}- </span>- <svg class="w-4 h-4 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3" />- </svg>- <span class="font-medium text-gray-800 dark:text-gray-200">- {corr.target_name || corr.target_id}- </span>- </div>- <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">- {corr.description || `${corr.event_pattern} (${corr.occurrences} observations)`}- </p>- <div class="flex items-center gap-3 mt-1 text-xs text-gray-500 dark:text-gray-400">- <span>Avg delay: {corr.avg_delay}</span>- <span>Confidence: {Math.round(corr.confidence * 100)}%</span>- </div>- </div>- )}- </For>- </div>- </div>- </Show>-- {/* Empty state */}- <Show when={!loading() && !locked() && totalInsights() === 0}>- <p class="text-sm text-gray-500 dark:text-gray-400 text-center py-2">- No predictions or correlations detected yet. The AI will learn patterns over time.- </p>- </Show>- </div>- </Show>- </div>- </Show>- );-};diff --git a/frontend-modern/src/components/shared/AIOverviewTable.tsx b/frontend-modern/src/components/shared/AIOverviewTable.tsxdeleted file mode 100644index 43c701a855..0000000000--- a/frontend-modern/src/components/shared/AIOverviewTable.tsx+++ /dev/null@@ -1,789 +0,0 @@-import { Component, createEffect, createSignal, For, Show } from 'solid-js';-import { AIAPI } from '@/api/ai';-import { logger } from '@/utils/logger';-import type { FailurePrediction, InfrastructureChange, RemediationRecord, RemediationStats, AnomalyReport } from '@/types/aiIntelligence';--const DEFAULT_UPGRADE_URL = 'https://pulserelay.pro/';--interface InsightRow {- id: string;- type: 'prediction' | 'impact' | 'memory' | 'anomaly';- typeBadge: string;- typeBadgeClass: string;- title: string;- subtitle: string;- timestamp: string;- confidence?: number;- locked: boolean;- badgeClass: string;-}--/**- * AIOverviewTable displays AI Insights, Pulse AI Impact, and Operational Memory- * in a unified, scannable table format- */-export const AIOverviewTable: Component<{ showWhenEmpty?: boolean }> = (props) => {- const [predictions, setPredictions] = createSignal<FailurePrediction[]>([]);- const [remediations, setRemediations] = createSignal<RemediationRecord[]>([]);- const [remediationStats, setRemediationStats] = createSignal<RemediationStats | null>(null);- const [changes, setChanges] = createSignal<InfrastructureChange[]>([]);- const [anomalies, setAnomalies] = createSignal<AnomalyReport[]>([]);- const [loading, setLoading] = createSignal(false);- const [error, setError] = createSignal('');-- // Locked states- const [insightsLocked, setInsightsLocked] = createSignal(false);- const [impactLocked, setImpactLocked] = createSignal(false);- const [memoryLocked, setMemoryLocked] = createSignal(false);- const [upgradeUrl, setUpgradeUrl] = createSignal(DEFAULT_UPGRADE_URL);-- // Locked counts (for locked state display)- const [insightsLockedCount, setInsightsLockedCount] = createSignal(0);- const [memoryLockedCount, setMemoryLockedCount] = createSignal(0);-- // Section expand/collapse state - default limits prevent overwhelming list- const [showAllActions, setShowAllActions] = createSignal(false);- const [showAllChanges, setShowAllChanges] = createSignal(false);-- // Limits for each section (when not expanded)- const ACTION_LIMIT = 5;- const CHANGE_LIMIT = 5;-- const showWhenEmpty = () => Boolean(props.showWhenEmpty);--- const loadData = async () => {- setLoading(true);- setError('');- try {- // Use allSettled so one failing endpoint doesn't break everything- const results = await Promise.allSettled([- AIAPI.getPredictions(),- AIAPI.getCorrelations(),- AIAPI.getRemediations({ hours: 168, limit: 6 }),- AIAPI.getRecentChanges(24),- AIAPI.getAnomalies(),- ]);-- // Extract results with fallbacks for failed requests- const predResp = results[0].status === 'fulfilled' ? results[0].value : { predictions: [], license_required: false, count: 0, upgrade_url: '' };- const corrResp = results[1].status === 'fulfilled' ? results[1].value : { correlations: [], license_required: false, count: 0, upgrade_url: '' };- const remResp = results[2].status === 'fulfilled' ? results[2].value : { remediations: [], license_required: false, stats: null, upgrade_url: '' };- const changesResp = results[3].status === 'fulfilled' ? results[3].value : { changes: [], license_required: false, count: 0, upgrade_url: '' };- const anomalyResp = results[4].status === 'fulfilled' ? results[4].value : { anomalies: [], count: 0, severity_counts: { critical: 0, high: 0, medium: 0, low: 0 } };--- // Handle anomalies (FREE - no license required)- setAnomalies(anomalyResp.anomalies || []);--- // Handle insights lock- const insightsLockedState = Boolean(predResp.license_required || corrResp.license_required);- setInsightsLocked(insightsLockedState);- if (insightsLockedState) {- const predCount = predResp.count || 0;- const corrCount = corrResp.count || 0;- setInsightsLockedCount(predCount + corrCount);- setPredictions([]);- } else {- setInsightsLockedCount(0);- setPredictions(predResp.predictions || []);- }-- // Handle impact lock- setImpactLocked(Boolean(remResp.license_required));- setRemediationStats(remResp.stats || null);- setRemediations(remResp.remediations || []);-- // Handle memory lock- const memoryLockedState = Boolean(changesResp.license_required);- setMemoryLocked(memoryLockedState);- if (memoryLockedState) {- setMemoryLockedCount(changesResp.count || 0);- setChanges([]);- } else {- setMemoryLockedCount(0);- setChanges(changesResp.changes || []);- }-- // Set upgrade URL from any response- setUpgradeUrl(- predResp.upgrade_url || corrResp.upgrade_url || remResp.upgrade_url || changesResp.upgrade_url || DEFAULT_UPGRADE_URL- );- } catch (e) {- logger.error('Failed to load AI overview data:', e);- setError('Failed to load AI overview data.');- } finally {- setLoading(false);- }- };-- createEffect(() => {- void loadData();- });-- // Format relative time- const formatRelativeTime = (ts: string) => {- const date = new Date(ts);- 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`;- if (diffDays < 7) return `${diffDays}d ago`;- return date.toLocaleDateString();- };-- // Format days until- const formatDaysUntil = (days: number) => {- if (days < 0) return 'Overdue';- if (days < 1) return 'Today';- if (days < 2) return 'Tomorrow';- return `In ${Math.round(days)} days`;- };-- // Build unified rows- const unifiedRows = (): InsightRow[] => {- const rows: InsightRow[] = [];-- // Anomalies (FREE - show at top since they're real-time)- for (const anomaly of anomalies()) {- const severityClasses: Record<string, string> = {- critical: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',- high: 'bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300',- medium: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',- low: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',- };- const badgeColors: Record<string, string> = {- critical: 'text-red-600 dark:text-red-400',- high: 'text-orange-600 dark:text-orange-400',- medium: 'text-amber-600 dark:text-amber-400',- low: 'text-blue-600 dark:text-blue-400',- };-- // Format the deviation ratio- const ratio = anomaly.baseline_mean > 0- ? (anomaly.current_value / anomaly.baseline_mean).toFixed(1)- : 'N/A';-- rows.push({- id: `anomaly-${anomaly.resource_id}-${anomaly.metric}`,- type: 'anomaly',- typeBadge: `${anomaly.severity.charAt(0).toUpperCase() + anomaly.severity.slice(1)} Anomaly`,- typeBadgeClass: severityClasses[anomaly.severity] || severityClasses.low,- title: `${anomaly.resource_name || anomaly.resource_id}: ${anomaly.metric.toUpperCase()} at ${ratio}x baseline`,- subtitle: anomaly.description || `Current: ${anomaly.current_value.toFixed(1)}%, Baseline: ${anomaly.baseline_mean.toFixed(1)}%`,- timestamp: 'Now',- locked: false,- badgeClass: badgeColors[anomaly.severity] || badgeColors.low,- });- }-- // Predictions- for (const pred of predictions()) {- const colorClass = pred.is_overdue || pred.days_until < 0- ? 'text-red-600 dark:text-red-400'- : pred.days_until < 3- ? 'text-amber-600 dark:text-amber-400'- : pred.days_until < 7- ? 'text-yellow-600 dark:text-yellow-400'- : 'text-blue-600 dark:text-blue-400';-- rows.push({- id: `pred-${pred.resource_id}-${pred.event_type}`,- type: 'prediction',- typeBadge: 'Prediction',- typeBadgeClass: 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300',- title: formatEventName(pred.event_type),- subtitle: pred.basis,- timestamp: formatDaysUntil(pred.days_until),- confidence: pred.confidence,- locked: false,- badgeClass: colorClass,- });- }------- // Remediations - ONLY show actual ACTIONS (restarts, resizes, cleanups, fixes)- // Skip diagnostic commands (df, grep, cat, tail, ps) - they don't provide lasting value- const isActionableCommand = (action: string): boolean => {- const cmd = action.trim().replace(/^\[[^\]]+\]\s*/, ''); // Strip [host] prefix- const actionPatterns = [- 'docker restart', 'docker start', 'docker stop', 'docker rm',- 'docker compose up', 'docker compose down', 'docker compose restart',- 'systemctl restart', 'systemctl start', 'systemctl stop', 'systemctl enable', 'systemctl disable',- 'service restart', 'service start', 'service stop',- 'pct resize', 'pct start', 'pct stop', 'pct shutdown', 'pct reboot',- 'qm resize', 'qm start', 'qm stop', 'qm shutdown', 'qm reboot',- 'rm -', 'rm /',- 'chmod', 'chown',- 'mkdir',- 'mv ', 'cp ',- 'apt install', 'apt upgrade', 'apt remove',- 'yum install', 'dnf install',- 'pip install', 'npm install',- 'kill ', 'pkill ', 'killall ',- 'reboot', 'shutdown',- ];- return actionPatterns.some(pattern => cmd.includes(pattern));- };-- const actionableRemediations = remediations().filter(rem => isActionableCommand(rem.action));- const visibleRemediations = showAllActions()- ? actionableRemediations- : actionableRemediations.slice(0, ACTION_LIMIT);-- for (const rem of visibleRemediations) {- // Get the title - skip if it's just the generic fallback- const title = rem.summary || summarizeValue(rem.problem, rem.action);- if (title === 'Ran diagnostic' || title === 'Executed command') {- continue; // Skip generic fallbacks - not actionable- }-- const outcomeBadgeClass: Record<string, string> = {- resolved: 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300',- partial: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',- failed: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',- };-- rows.push({- id: `rem-${rem.finding_id}-${rem.timestamp}`,- type: 'impact',- typeBadge: rem.outcome === 'resolved' ? 'Fixed' : rem.outcome === 'failed' ? 'Failed' : 'Action',- typeBadgeClass: outcomeBadgeClass[rem.outcome] || 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300',- title: title,- subtitle: rem.resource_name || '',- timestamp: formatRelativeTime(rem.timestamp),- locked: false,- badgeClass: 'text-emerald-600 dark:text-emerald-400',- });- }---- // Changes - only show meaningful changes, not noise- // Skip: created (just patrol discovering resources)- // Skip: backed_up (backups have their own section, no need to duplicate here)- // Skip: status changes from "unknown" (just startup, not real state changes)- const meaningfulChanges = changes().filter(c => {- if (c.change_type === 'created') return false;- if (c.change_type === 'backed_up') return false;- // Filter out startup noise: "unknown → running" or "unknown → stopped"- if (c.change_type === 'status' && c.description?.includes('unknown →')) return false;- return true;- });- const visibleChanges = showAllChanges()- ? meaningfulChanges- : meaningfulChanges.slice(0, CHANGE_LIMIT);--- for (const change of visibleChanges) {- const changeTypeBadgeClass: Record<string, string> = {- deleted: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',- config: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',- status: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',- migrated: 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300',- restarted: 'bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300',- backed_up: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',- };-- rows.push({- id: `change-${change.resource_id}-${change.detected_at}`,- type: 'memory',- typeBadge: formatChangeType(change.change_type),- typeBadgeClass: changeTypeBadgeClass[change.change_type] || 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300',- title: change.resource_name || change.resource_id,- subtitle: change.description || 'Change detected by Pulse Patrol.',- timestamp: formatRelativeTime(change.detected_at),- locked: false,- badgeClass: 'text-teal-600 dark:text-teal-400',- });- }--- return rows;- };-- const formatEventName = (eventType: string) => {- const names: Record<string, string> = {- high_memory: 'High Memory',- high_cpu: 'High CPU',- disk_full: 'Disk Full',- oom: 'Out of Memory',- restart: 'Restart',- unresponsive: 'Unresponsive',- backup_failed: 'Backup Failure',- };- if (names[eventType]) return names[eventType];- return eventType- .split(/[_-]/)- .map(part => {- if (part === 'cpu') return 'CPU';- if (part === 'vm') return 'VM';- if (part === 'pbs') return 'PBS';- if (part === 'raid') return 'RAID';- return part.charAt(0).toUpperCase() + part.slice(1);- })- .join(' ');- };-- const formatChangeType = (changeType: string) => {- const labels: Record<string, string> = {- created: 'Created',- deleted: 'Deleted',- config: 'Config',- status: 'Status',- migrated: 'Migrated',- restarted: 'Restarted',- backed_up: 'Backup',- };- if (labels[changeType]) return labels[changeType];- return changeType.split(/[_-]/).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join(' ');- };-- // Summarize a shell command action into a human-readable description- // Prefixed with underscore - not currently used but kept for future expansion- const _summarizeAction = (action: string): { title: string; subtitle: string } => {- const cmd = action.trim();-- // Common command patterns and their summaries- if (cmd.includes('df -h') || cmd.includes('du -s')) {- const pathMatch = cmd.match(/\/([\w/.-]+)/);- const path = pathMatch ? pathMatch[0] : 'storage';- return {- title: 'Checked disk usage',- subtitle: `Analyzed space on ${path}`- };- }- if (cmd.includes('docker ps') || cmd.includes('docker status')) {- const containerMatch = cmd.match(/name[=:]?\s*(\w+)/i);- const container = containerMatch ? containerMatch[1] : 'containers';- return {- title: 'Checked container status',- subtitle: `Verified ${container} is running`- };- }- if (cmd.includes('docker restart') || cmd.includes('docker start')) {- const containerMatch = cmd.match(/(?:restart|start)\s+(\w+)/i);- const container = containerMatch ? containerMatch[1] : 'container';- return {- title: 'Restarted container',- subtitle: `Restored ${container} service`- };- }- if (cmd.includes('systemctl restart') || (cmd.includes('service') && cmd.includes('restart'))) {- const serviceMatch = cmd.match(/(?:restart|start)\s+(\S+)/i);- const service = serviceMatch ? serviceMatch[1] : 'service';- return {- title: 'Restarted service',- subtitle: `Restored ${service}`- };- }- if (cmd.includes('grep') && cmd.includes('config')) {- return {- title: 'Checked configuration',- subtitle: 'Verified config settings'- };- }- if (cmd.includes('grep')) {- return {- title: 'Searched logs/config',- subtitle: 'Retrieved diagnostic information'- };- }- if (cmd.includes('tail') || cmd.includes('cat') || cmd.includes('head')) {- return {- title: 'Inspected logs/files',- subtitle: 'Retrieved diagnostic information'- };- }- if (cmd.includes('ps aux') || cmd.includes('top') || cmd.includes('htop')) {- return {- title: 'Checked processes',- subtitle: 'Analyzed running processes'- };- }- if (cmd.includes('free') || cmd.includes('memory')) {- return {- title: 'Checked memory usage',- subtitle: 'Analyzed memory allocation'- };- }- if (cmd.includes('ping') || cmd.includes('curl') || cmd.includes('wget')) {- return {- title: 'Tested connectivity',- subtitle: 'Verified network connection'- };- }- if (cmd.startsWith('[host]') || cmd.startsWith('[')) {- // Agent command - extract the actual command- const innerCmd = cmd.replace(/^\[[\w\s]+\]\s*/, '');- const inner = _summarizeAction(innerCmd);- return {- title: inner.title,- subtitle: `${inner.subtitle} (via agent)`- };- }-- // Fallback: truncate and show the command- const truncated = cmd.length > 50 ? cmd.substring(0, 47) + '...' : cmd;- return {- title: 'Executed command',- subtitle: truncated- };- };-- // Create a meaningful summary from the ACTION (command) only- // The problem field is just chat context and not useful here- const summarizeValue = (_problem: string, action: string): string => {- const cmd = action.trim();-- // Extract target/context from the command (container names, paths, services)- const extractTarget = (): string | null => {- // Container name from docker commands- const containerMatch = cmd.match(/name[=:]?\s*(\w+)/i) || cmd.match(/filter.*?(\w+)/);- if (containerMatch) return containerMatch[1];-- // Service name from systemctl- const serviceMatch = cmd.match(/systemctl\s+\w+\s+(\S+)/);- if (serviceMatch) return serviceMatch[1];-- // Path for disk commands - get the meaningful part- const pathMatch = cmd.match(/\/([\w]+)(?:\/[\w_-]+)*(?:\s|$)/);- if (pathMatch) {- const fullPath = cmd.match(/\/[\w\/_-]+/)?.[0] || '';- // Extract meaningful name from path- if (fullPath.includes('frigate')) return 'Frigate';- if (fullPath.includes('plex')) return 'Plex';- if (fullPath.includes('docker')) return 'Docker';- if (fullPath.includes('recordings')) return 'recordings';- if (fullPath.includes('media')) return 'media';- if (fullPath.includes('config')) return 'config';- return fullPath.split('/').filter(Boolean).pop() || null;- }-- // Config file reference- if (cmd.includes('config.yml') || cmd.includes('config.yaml')) return 'config';-- return null;- };-- const target = extractTarget();- const targetStr = target ? ` (${target})` : '';-- // Generate meaningful descriptions based on command type- if (cmd.includes('docker restart') || cmd.includes('docker start')) {- return `Restarted container${targetStr}`;- }- if (cmd.includes('docker stop')) {- return `Stopped container${targetStr}`;- }- if (cmd.includes('docker ps') || cmd.includes('docker status')) {- return `Verified container status${targetStr}`;- }- if (cmd.includes('docker logs')) {- return `Retrieved container logs${targetStr}`;- }- if (cmd.includes('systemctl restart') || cmd.includes('service') && cmd.includes('restart')) {- return `Restarted service${targetStr}`;- }- if (cmd.includes('systemctl status')) {- return `Checked service status${targetStr}`;- }- if ((cmd.includes('df') || cmd.includes('du')) && target) {- return `Analyzed storage usage${targetStr}`;- }- if (cmd.includes('df') || cmd.includes('du')) {- return 'Analyzed disk space';- }- if (cmd.includes('grep') && (cmd.includes('config') || cmd.includes('.yml') || cmd.includes('.yaml'))) {- return `Inspected configuration${targetStr}`;- }- if (cmd.includes('grep') || cmd.includes('tail -f') || cmd.includes('journalctl')) {- return `Reviewed logs${targetStr}`;- }- if (cmd.includes('tail') || cmd.includes('cat') || cmd.includes('head')) {- return `Retrieved file contents${targetStr}`;- }- if (cmd.includes('ping') || cmd.includes('curl') || cmd.includes('wget')) {- return 'Tested network connectivity';- }- if (cmd.includes('free') || cmd.includes('/proc/meminfo')) {- return 'Checked memory usage';- }- if (cmd.includes('ps aux') || cmd.includes('top') || cmd.includes('htop')) {- return 'Analyzed running processes';- }- if (cmd.includes('chmod') || cmd.includes('chown')) {- return `Fixed permissions${targetStr}`;- }- if (cmd.includes('rm ') || cmd.includes('rm -')) {- return `Cleaned up files${targetStr}`;- }- if (cmd.includes('mkdir')) {- return `Created directory${targetStr}`;- }- if (cmd.startsWith('[host]') || cmd.startsWith('[')) {- // Agent command - recurse with inner command- const innerCmd = cmd.replace(/^\[[\w\s]+\]\s*/, '');- return summarizeValue('', innerCmd);- }-- return 'Ran diagnostic';- };-- const totalItems = () => unifiedRows().length;- const anyLocked = () => insightsLocked() || impactLocked() || memoryLocked();-- const shouldShow = () => showWhenEmpty() || loading() || totalItems() > 0 || anyLocked();-- // Stats for quick summary- const statsDisplay = () => {- const stats = remediationStats();- if (!stats) return null;- return stats;- };-- // Calculate hidden items per section- const hiddenDependencies = () => {- // Correlations hidden from display - always return 0- return 0;- };--- const hiddenActions = () => {- const actionable = remediations().filter(rem => {- const cmd = rem.action.trim().replace(/^\[[^\]]+\]\s*/, '');- const patterns = ['docker restart', 'docker start', 'systemctl restart', 'pct resize', 'qm resize', 'rm -', 'chmod', 'chown', 'reboot'];- return patterns.some(p => cmd.includes(p));- });- return showAllActions() ? 0 : Math.max(0, actionable.length - ACTION_LIMIT);- };- const hiddenChanges = () => {- const meaningful = changes().filter(c => c.change_type !== 'created');- return showAllChanges() ? 0 : Math.max(0, meaningful.length - CHANGE_LIMIT);- };- const anyHidden = () => hiddenDependencies() > 0 || hiddenActions() > 0 || hiddenChanges() > 0;-- return (- <Show when={shouldShow()}>- <div class="bg-white dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden shadow-sm">- {/* Header */}- <div class="px-4 py-3 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-purple-50 via-emerald-50 to-teal-50 dark:from-purple-900/20 dark:via-emerald-900/20 dark:to-teal-900/20">- <div class="flex items-center justify-between flex-wrap gap-2">- <div class="flex items-center gap-3">- <div class="flex items-center gap-1.5">- <svg class="w-5 h-5 text-purple-600 dark:text-purple-400" 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>- <span class="font-semibold text-gray-900 dark:text-gray-100">Pulse Intelligence Summary</span>- </div>- <Show when={totalItems() > 0}>- <span class="px-2 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded-full">- {totalItems()} items- </span>- </Show>- <Show when={anyLocked()}>- <span class="px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 rounded-full">- Some Locked- </span>- </Show>- </div>-- {/* Quick Stats */}- <Show when={statsDisplay()}>- <div class="flex items-center gap-3 text-xs">- <div class="flex items-center gap-1">- <span class="text-green-600 dark:text-green-400">✓</span>- <span class="text-gray-600 dark:text-gray-400">{statsDisplay()!.resolved} resolved</span>- </div>- <div class="flex items-center gap-1">- <span class="text-blue-600 dark:text-blue-400">⚡</span>- <span class="text-gray-600 dark:text-gray-400">{statsDisplay()!.automatic} auto-fix</span>- </div>- </div>- </Show>- </div>- </div>-- {/* Loading */}- <Show when={loading()}>- <div class="px-4 py-6 text-center">- <div class="inline-flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400">- <span class="h-4 w-4 border-2 border-current border-t-transparent rounded-full animate-spin" />- Loading AI intelligence...- </div>- </div>- </Show>-- {/* Error */}- <Show when={error() && !loading()}>- <div class="px-4 py-4">- <div class="text-sm text-red-600 dark:text-red-400">{error()}</div>- </div>- </Show>-- {/* Locked notice (if all are locked) */}- <Show when={insightsLocked() && impactLocked() && memoryLocked() && !loading()}>- <div class="px-4 py-4">- <div class="rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 p-3 text-sm text-amber-800 dark:text-amber-200">- <div class="flex items-center justify-between gap-3">- <div>- <p class="font-medium">Pulse Pro required</p>- <p class="text-xs text-amber-700 dark:text-amber-300 mt-1">- Full AI intelligence features including predictions, impact tracking, and operational memory require Pulse Pro.- </p>- </div>- <a- class="text-xs font-medium text-amber-800 dark:text-amber-200 underline whitespace-nowrap"- href={upgradeUrl()}- target="_blank"- rel="noreferrer"- >- Upgrade- </a>- </div>- </div>- </div>- </Show>-- {/* Table */}- <Show when={!loading() && (totalItems() > 0 || !anyLocked())}>- <Show- when={totalItems() > 0}- fallback={- <div class="px-4 py-8 text-center">- <div class="inline-flex flex-col items-center gap-2">- <svg class="w-10 h-10 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.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>- <p class="text-sm text-gray-500 dark:text-gray-400">- No Pulse insights yet. Pulse will learn patterns and surface intelligence over time.- </p>- </div>- </div>- }- >- <div class="overflow-x-auto">- <table class="w-full text-sm">- <thead>- <tr class="bg-gray-50 dark:bg-gray-800/80 text-gray-600 dark:text-gray-400 border-b border-gray-200 dark:border-gray-700">- <th class="px-4 py-2 text-left text-xs font-medium uppercase tracking-wider w-24">Type</th>- <th class="px-4 py-2 text-left text-xs font-medium uppercase tracking-wider">Details</th>- <th class="px-4 py-2 text-right text-xs font-medium uppercase tracking-wider w-24">When</th>- </tr>- </thead>- <tbody class="divide-y divide-gray-100 dark:divide-gray-700/50">- <For each={unifiedRows()}>- {(row) => (- <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/40 transition-colors">- <td class="px-4 py-2.5">- <span class={`inline-flex px-2 py-0.5 text-[10px] font-semibold rounded-full whitespace-nowrap ${row.typeBadgeClass}`}>- {row.typeBadge}- </span>- </td>- <td class="px-4 py-2.5">- <div class="flex flex-col gap-0.5">- <span class={`font-medium text-gray-800 dark:text-gray-200 ${row.badgeClass}`}>- {row.title}- </span>- <span class="text-xs text-gray-500 dark:text-gray-400 line-clamp-1">- {row.subtitle}- </span>- </div>- <Show when={row.confidence !== undefined}>- <span class="text-[10px] text-gray-400 dark:text-gray-500">- {Math.round(row.confidence! * 100)}% confidence- </span>- </Show>- </td>- <td class="px-4 py-2.5 text-right">- <span class="text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">- {row.timestamp}- </span>- </td>- </tr>- )}- </For>- </tbody>- </table>- </div>- </Show>- </Show>-- {/* Show more buttons (if any hidden) */}- <Show when={!loading() && anyHidden()}>- <div class="px-4 py-2 border-t border-gray-100 dark:border-gray-700/50 bg-gray-50/50 dark:bg-gray-800/30">- <div class="flex flex-wrap items-center gap-3 text-xs">- <Show when={hiddenActions() > 0}>- <button- class="text-emerald-600 dark:text-emerald-400 hover:underline"- onClick={() => setShowAllActions(true)}- >- + {hiddenActions()} more actions- </button>- </Show>- <Show when={hiddenChanges() > 0}>- <button- class="text-teal-600 dark:text-teal-400 hover:underline"- onClick={() => setShowAllChanges(true)}- >- + {hiddenChanges()} more changes- </button>- </Show>- </div>- </div>- </Show>-- {/* Section locked notices (partial lock) */}-- <Show when={!loading() && anyLocked() && !(insightsLocked() && impactLocked() && memoryLocked())}>- <div class="px-4 py-3 border-t border-gray-200 dark:border-gray-700 bg-amber-50/50 dark:bg-amber-900/10">- <div class="flex flex-wrap items-center gap-4 text-xs">- <Show when={insightsLocked()}>- <div class="flex items-center gap-1 text-amber-700 dark:text-amber-300">- <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="M12 15V11m0 0V7m0 4h4m-4 0H8" />- </svg>- <span>{insightsLockedCount()} Pulse Insights locked</span>- </div>- </Show>- <Show when={impactLocked()}>- <div class="flex items-center gap-1 text-amber-700 dark:text-amber-300">- <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="M13 10V3L4 14h7v7l9-11h-7z" />- </svg>- <span>Impact details locked</span>- </div>- </Show>- <Show when={memoryLocked()}>- <div class="flex items-center gap-1 text-amber-700 dark:text-amber-300">- <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="M9 12h6m-6 4h6m2 4H7a2 2 0 01-2-2V7a2 2 0 012-2h5l5 5v9a2 2 0 01-2 2z" />- </svg>- <span>{memoryLockedCount()} changes locked</span>- </div>- </Show>- <a- class="ml-auto text-amber-800 dark:text-amber-200 font-medium underline"- href={upgradeUrl()}- target="_blank"- rel="noreferrer"- >- Upgrade to Pulse Pro- </a>- </div>- </div>- </Show>- </div>- </Show>- );-};diff --git a/frontend-modern/src/components/shared/AIRecentChangesPanel.tsx b/frontend-modern/src/components/shared/AIRecentChangesPanel.tsxdeleted file mode 100644index b2274a759c..0000000000--- a/frontend-modern/src/components/shared/AIRecentChangesPanel.tsx+++ /dev/null@@ -1,198 +0,0 @@-import { Component, createEffect, createSignal, For, Show } from 'solid-js';-import { AIAPI } from '@/api/ai';-import { logger } from '@/utils/logger';-import type { InfrastructureChange } from '@/types/aiIntelligence';--const DEFAULT_UPGRADE_URL = 'https://pulserelay.pro/';--export const AIRecentChangesPanel: Component<{ hours?: number; showWhenEmpty?: boolean }> = (props) => {- const [changes, setChanges] = createSignal<InfrastructureChange[]>([]);- const [loading, setLoading] = createSignal(false);- const [locked, setLocked] = createSignal(false);- const [lockedCount, setLockedCount] = createSignal(0);- const [upgradeUrl, setUpgradeUrl] = createSignal(DEFAULT_UPGRADE_URL);- const [error, setError] = createSignal('');- const showWhenEmpty = () => Boolean(props.showWhenEmpty);- const hours = () => props.hours ?? 24;-- const loadData = async () => {- setLoading(true);- setError('');- try {- const response = await AIAPI.getRecentChanges(hours());- const licenseLocked = Boolean(response.license_required);- setLocked(licenseLocked);- setUpgradeUrl(response.upgrade_url || DEFAULT_UPGRADE_URL);- if (licenseLocked) {- setLockedCount(response.count || 0);- setChanges([]);- } else {- setLockedCount(0);- setChanges(response.changes || []);- }- } catch (e) {- logger.error('Failed to load AI change history:', e);- setError('Failed to load recent changes.');- } finally {- setLoading(false);- }- };-- createEffect(() => {- void loadData();- });-- const displayedChanges = () => changes().slice(0, 6);- const shouldShow = () => showWhenEmpty() || loading() || displayedChanges().length > 0 || lockedCount() > 0;-- const formatRelativeTime = (ts: string) => {- const date = new Date(ts);- 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`;- if (diffDays < 7) return `${diffDays}d ago`;- return date.toLocaleDateString();- };-- const changeTypeLabel = (changeType: string) => {- const labels: Record<string, string> = {- created: 'Created',- deleted: 'Deleted',- config: 'Config change',- status: 'Status change',- migrated: 'Migrated',- restarted: 'Restarted',- backed_up: 'Backup completed',- };- if (labels[changeType]) {- return labels[changeType];- }- return changeType- .split(/[_-]/)- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))- .join(' ');- };-- const changeTypeBadge = (changeType: string) => {- const styles: Record<string, string> = {- created: 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300',- deleted: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',- config: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',- status: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',- migrated: 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300',- restarted: 'bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300',- backed_up: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',- };- return styles[changeType] || 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300';- };-- return (- <Show when={shouldShow()}>- <div class="bg-gradient-to-r from-slate-50 to-teal-50 dark:from-slate-900/20 dark:to-teal-900/20 border border-slate-200 dark:border-slate-700 rounded-lg overflow-hidden">- <div class="px-4 py-3 flex items-center justify-between border-b border-slate-200/70 dark:border-slate-700/70">- <div class="flex items-center gap-2">- <svg class="w-5 h-5 text-teal-600 dark:text-teal-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 4H7a2 2 0 01-2-2V7a2 2 0 012-2h5l5 5v9a2 2 0 01-2 2z" />- </svg>- <span class="font-medium text-slate-900 dark:text-slate-100">Operational Memory</span>- <Show when={lockedCount() > 0 && locked()}>- <span class="px-2 py-0.5 text-xs font-medium bg-teal-200 dark:bg-teal-700 text-teal-900 dark:text-teal-100 rounded-full">- {lockedCount()}- </span>- </Show>- <Show when={!locked() && displayedChanges().length > 0}>- <span class="px-2 py-0.5 text-xs font-medium bg-teal-200 dark:bg-teal-700 text-teal-900 dark:text-teal-100 rounded-full">- {displayedChanges().length}- </span>- </Show>- <Show when={locked()}>- <span class="px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 rounded-full">- Locked- </span>- </Show>- </div>- <span class="text-xs text-slate-500 dark:text-slate-400">{hours()}h window</span>- </div>- <div class="px-4 pb-4 space-y-3">- <Show when={loading()}>- <div class="text-sm text-slate-500 dark:text-slate-400 flex items-center gap-2">- <span class="h-4 w-4 border-2 border-current border-t-transparent rounded-full animate-spin" />- Loading changes...- </div>- </Show>-- <Show when={error() && !loading()}>- <div class="text-sm text-red-600 dark:text-red-400">- {error()}- </div>- </Show>-- <Show when={locked() && !loading()}>- <div class="rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 p-3 text-sm text-amber-800 dark:text-amber-200">- <div class="flex items-center justify-between gap-3">- <div>- <p class="font-medium">Pulse Pro required</p>- <p class="text-xs text-amber-700 dark:text-amber-300 mt-1">- Operational memory is available with Pulse Pro. {lockedCount() || 0} changes are ready to review.- </p>- </div>- <a- class="text-xs font-medium text-amber-800 dark:text-amber-200 underline"- href={upgradeUrl()}- target="_blank"- rel="noreferrer"- >- Upgrade- </a>- </div>- </div>- </Show>-- <Show when={!locked() && !loading()}>- <Show- when={displayedChanges().length > 0}- fallback={- <p class="text-sm text-slate-500 dark:text-slate-400 text-center py-2">- No recent changes detected. The AI will surface configuration and state changes here.- </p>- }- >- <div class="space-y-2">- <For each={displayedChanges()}>- {(change) => (- <div class="bg-white/60 dark:bg-slate-900/40 border border-slate-100 dark:border-slate-800 rounded-lg p-3">- <div class="flex items-start justify-between gap-3">- <div class="flex-1">- <div class="flex items-center gap-2 flex-wrap">- <span class={`px-2 py-0.5 text-[10px] font-semibold rounded-full ${changeTypeBadge(change.change_type)}`}>- {changeTypeLabel(change.change_type)}- </span>- <span class="text-sm font-medium text-slate-800 dark:text-slate-200">- {change.resource_name || change.resource_id}- </span>- </div>- <p class="text-xs text-slate-600 dark:text-slate-400 mt-1">- {change.description || 'Change detected by Pulse Patrol.'}- </p>- </div>- <span class="text-xs text-slate-500 dark:text-slate-400 whitespace-nowrap">- {formatRelativeTime(change.detected_at)}- </span>- </div>- </div>- )}- </For>- </div>- </Show>- </Show>- </div>- </div>- </Show>- );-};diff --git a/frontend-modern/src/components/shared/FeatureTip.tsx b/frontend-modern/src/components/shared/FeatureTip.tsxdeleted file mode 100644index 2312dabc0a..0000000000--- a/frontend-modern/src/components/shared/FeatureTip.tsx+++ /dev/null@@ -1,129 +0,0 @@-import { Component, Show } from 'solid-js';-import { A } from '@solidjs/router';-import X from 'lucide-solid/icons/x';-import Lightbulb from 'lucide-solid/icons/lightbulb';-import ArrowRight from 'lucide-solid/icons/arrow-right';-import type { FeatureTip as FeatureTipType } from '@/content/features';-import { dismissTip, isTipDismissed } from '@/stores/featureTips';--export interface FeatureTipProps {- /** The feature tip to display */- tip: FeatureTipType;-- /** Display variant */- variant?: 'inline' | 'banner' | 'compact';-- /** Additional CSS classes */- class?: string;-- /** Called when the tip is dismissed */- onDismiss?: () => void;-}--export const FeatureTip: Component<FeatureTipProps> = (props) => {- // Don't render if already dismissed- if (isTipDismissed(props.tip.id)) {- return null;- }-- const variant = () => props.variant ?? 'inline';-- const handleDismiss = (e: MouseEvent) => {- e.preventDefault();- e.stopPropagation();- dismissTip(props.tip.id);- props.onDismiss?.();- };-- // Inline variant - small, subtle- if (variant() === 'inline') {- return (- <div- class={`flex items-start gap-2 p-2 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg text-xs ${props.class ?? ''}`}- >- <Lightbulb class="w-3.5 h-3.5 text-blue-500 flex-shrink-0 mt-0.5" strokeWidth={2} />- <div class="flex-1 min-w-0">- <span class="text-blue-800 dark:text-blue-200">{props.tip.description}</span>- <Show when={props.tip.action}>- <A- href={props.tip.action!.path}- class="ml-1 text-blue-600 dark:text-blue-400 hover:underline font-medium"- >- {props.tip.action!.label}- </A>- </Show>- </div>- <button- type="button"- onClick={handleDismiss}- class="p-0.5 text-blue-400 hover:text-blue-600 dark:hover:text-blue-300 rounded transition-colors flex-shrink-0"- aria-label="Dismiss tip"- >- <X class="w-3 h-3" strokeWidth={2} />- </button>- </div>- );- }-- // Compact variant - single line- if (variant() === 'compact') {- return (- <div- class={`flex items-center gap-2 px-2 py-1 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded text-xs ${props.class ?? ''}`}- >- <Lightbulb class="w-3 h-3 text-amber-500 flex-shrink-0" strokeWidth={2} />- <span class="text-amber-800 dark:text-amber-200 truncate">{props.tip.title}</span>- <Show when={props.tip.action}>- <A- href={props.tip.action!.path}- class="text-amber-600 dark:text-amber-400 hover:underline flex items-center gap-0.5"- >- <ArrowRight class="w-3 h-3" strokeWidth={2} />- </A>- </Show>- <button- type="button"- onClick={handleDismiss}- class="p-0.5 text-amber-400 hover:text-amber-600 dark:hover:text-amber-300 rounded transition-colors flex-shrink-0 ml-auto"- aria-label="Dismiss tip"- >- <X class="w-3 h-3" strokeWidth={2} />- </button>- </div>- );- }-- // Banner variant - full width, more prominent- return (- <div- class={`flex items-start gap-3 p-3 bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 border border-blue-200 dark:border-blue-800 rounded-lg ${props.class ?? ''}`}- >- <div class="p-1.5 bg-blue-100 dark:bg-blue-800 rounded-lg flex-shrink-0">- <Lightbulb class="w-4 h-4 text-blue-600 dark:text-blue-300" strokeWidth={2} />- </div>- <div class="flex-1 min-w-0">- <div class="text-sm font-medium text-blue-900 dark:text-blue-100">{props.tip.title}</div>- <p class="text-xs text-blue-700 dark:text-blue-300 mt-0.5">{props.tip.description}</p>- <Show when={props.tip.action}>- <A- href={props.tip.action!.path}- class="inline-flex items-center gap-1 mt-2 text-xs font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"- >- {props.tip.action!.label}- <ArrowRight class="w-3 h-3" strokeWidth={2} />- </A>- </Show>- </div>- <button- type="button"- onClick={handleDismiss}- class="p-1 text-blue-400 hover:text-blue-600 dark:hover:text-blue-300 hover:bg-blue-100 dark:hover:bg-blue-800 rounded transition-colors flex-shrink-0"- aria-label="Dismiss tip"- >- <X class="w-4 h-4" strokeWidth={2} />- </button>- </div>- );-};--export default FeatureTip;diff --git a/frontend-modern/src/components/shared/OnlineStatusBadge.tsx b/frontend-modern/src/components/shared/OnlineStatusBadge.tsxdeleted file mode 100644index f5c2ec06b4..0000000000--- a/frontend-modern/src/components/shared/OnlineStatusBadge.tsx+++ /dev/null@@ -1,29 +0,0 @@-import { Component } from 'solid-js';-import type { StatusIndicatorVariant } from '@/utils/status';--interface OnlineStatusBadgeProps {- variant: StatusIndicatorVariant;- label: string;- class?: string;-}--const variantClasses: Record<StatusIndicatorVariant, string> = {- success: 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300',- warning: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',- danger: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',- muted: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400',-};--/**- * OnlineStatusBadge - A pill-shaped badge showing online/offline/degraded status- * Used in tables to show resource status (nodes, guests, containers, etc.)- */-export const OnlineStatusBadge: Component<OnlineStatusBadgeProps> = (props) => {- return (- <span- class={`inline-flex items-center justify-center rounded-full px-2 py-0.5 text-[10px] font-semibold whitespace-nowrap ${variantClasses[props.variant]} ${props.class || ''}`}- >- {props.label}- </span>- );-};diff --git a/frontend-modern/src/content/features/index.ts b/frontend-modern/src/content/features/index.tsdeleted file mode 100644index 0fad7b73b2..0000000000--- a/frontend-modern/src/content/features/index.ts+++ /dev/null@@ -1,94 +0,0 @@-/**- * Feature Discovery Registry- *- * Central export point for feature tips and What's New content.- */--import type { FeatureTip } from './types';--// Feature tips for discoverable features-const featureTips: FeatureTip[] = [- {- id: 'alert-delay-thresholds',- title: 'Alert Delay Thresholds',- description:- 'Click the clock icon to set how long a threshold must be exceeded before an alert fires. Prevents alerts from brief spikes.',- location: 'alerts',- addedInVersion: 'v5.0.0',- action: {- label: 'Go to Alerts',- path: '/alerts',- },- priority: 10,- },- {- id: 'custom-ai-endpoints',- title: 'Custom AI Endpoints',- description:- 'Use OpenRouter, vLLM, or any OpenAI-compatible API. Expand the OpenAI section in AI Settings and enter your provider\'s base URL.',- location: 'settings',- addedInVersion: 'v4.5.0',- action: {- label: 'Configure AI',- path: '/settings',- },- priority: 8,- },- {- id: 'container-update-detection',- title: 'Container Update Detection',- description:- 'Pulse checks for container image updates automatically. Look for the blue badge on containers with available updates.',- location: 'docker',- addedInVersion: 'v5.0.11',- action: {- label: 'View Containers',- path: '/docker',- },- priority: 7,- },- {- id: 'sparkline-metrics',- title: 'Sparkline Metrics',- description:- 'Toggle between bar charts and sparklines for CPU/Memory metrics. Click the chart icon in the column header.',- location: 'dashboard',- addedInVersion: 'v4.0.0',- priority: 5,- },- {- id: 'column-customization',- title: 'Customize Columns',- description:- 'Click "Columns" to show/hide table columns. Your preferences are saved automatically.',- location: 'dashboard',- addedInVersion: 'v4.0.0',- priority: 4,- },-];--/**- * Get all feature tips- */-export function getAllFeatureTips(): FeatureTip[] {- return [...featureTips].sort((a, b) => (b.priority || 0) - (a.priority || 0));-}--/**- * Get feature tips for a specific location- */-export function getFeatureTipsForLocation(location: FeatureTip['location']): FeatureTip[] {- return featureTips- .filter((tip) => tip.location === location || tip.location === 'global')- .sort((a, b) => (b.priority || 0) - (a.priority || 0));-}--/**- * Get a specific feature tip by ID- */-export function getFeatureTip(id: string): FeatureTip | undefined {- return featureTips.find((tip) => tip.id === id);-}--// Re-export types-export type { FeatureTip } from './types';diff --git a/frontend-modern/src/content/features/types.ts b/frontend-modern/src/content/features/types.tsdeleted file mode 100644index ee1139f04e..0000000000--- a/frontend-modern/src/content/features/types.ts+++ /dev/null@@ -1,29 +0,0 @@-/**- * Feature Tip - A discoverable feature that users might not know about- */-export interface FeatureTip {- /** Unique identifier for this tip */- id: string;-- /** Short title for the tip */- title: string;-- /** Description explaining the feature */- description: string;-- /** Where this tip should appear in the UI */- location: 'alerts' | 'settings' | 'docker' | 'dashboard' | 'hosts' | 'global';-- /** Version when this feature was added */- addedInVersion: string;-- /** Optional call to action */- action?: {- label: string;- path: string;- };-- /** Priority for display order (higher = more important) */- priority?: number;-}-diff --git a/frontend-modern/src/stores/featureTips.ts b/frontend-modern/src/stores/featureTips.tsdeleted file mode 100644index a6d2ef70ad..0000000000--- a/frontend-modern/src/stores/featureTips.ts+++ /dev/null@@ -1,112 +0,0 @@-/**- * Feature Tips Store- *- * Manages feature discovery state:- * - Which feature tips have been dismissed- * - Provides functions to check and update discovery state- */--import { createSignal } from 'solid-js';-import { logger } from '@/utils/logger';-import { STORAGE_KEYS } from '@/utils/localStorage';-import {- getAllFeatureTips,- getFeatureTipsForLocation,- type FeatureTip,-} from '@/content/features';--// Read dismissed tips from localStorage-const getInitialDismissedTips = (): Set<string> => {- if (typeof window === 'undefined') return new Set();-- try {- const stored = localStorage.getItem(STORAGE_KEYS.DISMISSED_FEATURE_TIPS);- if (stored) {- const parsed = JSON.parse(stored);- if (Array.isArray(parsed)) {- return new Set(parsed);- }- }- } catch (_err) {- // Ignore localStorage errors- }-- return new Set();-};--// Create signals-const [dismissedTips, setDismissedTips] = createSignal<Set<string>>(getInitialDismissedTips());--/**- * Check if a feature tip has been dismissed- */-export function isTipDismissed(tipId: string): boolean {- return dismissedTips().has(tipId);-}--/**- * Dismiss a feature tip and persist to localStorage- */-export function dismissTip(tipId: string): void {- const current = dismissedTips();- if (current.has(tipId)) return;-- const updated = new Set(current);- updated.add(tipId);- setDismissedTips(updated);-- if (typeof window !== 'undefined') {- try {- localStorage.setItem(STORAGE_KEYS.DISMISSED_FEATURE_TIPS, JSON.stringify([...updated]));- } catch (err) {- logger.warn('Failed to save dismissed tips', err);- }- }-}--/**- * Reset all dismissed tips (useful for testing)- */-export function resetDismissedTips(): void {- setDismissedTips(new Set<string>());-- if (typeof window !== 'undefined') {- try {- localStorage.removeItem(STORAGE_KEYS.DISMISSED_FEATURE_TIPS);- } catch (err) {- logger.warn('Failed to reset dismissed tips', err);- }- }-}--/**- * Get undismissed feature tips for a location- */-export function getUndismissedTipsForLocation(location: FeatureTip['location']): FeatureTip[] {- const tips = getFeatureTipsForLocation(location);- const dismissed = dismissedTips();- return tips.filter((tip) => !dismissed.has(tip.id));-}--/**- * Get all undismissed feature tips- */-export function getAllUndismissedTips(): FeatureTip[] {- const tips = getAllFeatureTips();- const dismissed = dismissedTips();- return tips.filter((tip) => !dismissed.has(tip.id));-}--/**- * Hook for components to use feature tips state- */-export function useFeatureTips() {- return {- dismissedTips,- isTipDismissed,- dismissTip,- resetDismissedTips,- getUndismissedTipsForLocation,- getAllUndismissedTips,- };-}diff --git a/frontend-modern/src/utils/anomalyColors.ts b/frontend-modern/src/utils/anomalyColors.tsdeleted file mode 100644index 9ab72aa3a0..0000000000--- a/frontend-modern/src/utils/anomalyColors.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Anomaly severity color classes for Tailwind CSS.- * Used by metric bar components to display anomaly indicators.- */-export const anomalySeverityClass: Record<string, string> = {- critical: 'text-red-400',- high: 'text-orange-400',- medium: 'text-yellow-400',- low: 'text-blue-400',-};--/**- * Get the appropriate CSS class for an anomaly severity level.- * Falls back to yellow-400 if severity is unknown.- */-export function getAnomalySeverityClass(severity: string): string {- return anomalySeverityClass[severity] || 'text-yellow-400';-}diff --git a/internal/ai/dryrun/simulator.go b/internal/ai/dryrun/simulator.godeleted file mode 100644index b5a7573237..0000000000--- a/internal/ai/dryrun/simulator.go+++ /dev/null@@ -1,414 +0,0 @@-package dryrun--import (- "fmt"- "regexp"- "strings"-)--// SimulationResult contains the simulated output of a command.-type SimulationResult struct {- Output string `json:"output"`- ExitCode int `json:"exitCode"`- WouldDo string `json:"wouldDo"` // Human-readable description- Reversible bool `json:"reversible"` // Whether this action can be undone- RollbackCmd string `json:"rollbackCmd"` // Command to undo (if reversible)- Simulated bool `json:"simulated"` // Always true for dry-run-}--// simulationPattern defines how to simulate a command pattern.-type simulationPattern struct {- match *regexp.Regexp- generate func(cmd string, matches []string) SimulationResult-}--// Simulator provides dry-run simulation for commands.-type Simulator struct {- patterns []simulationPattern-}--// NewSimulator creates a new command simulator.-func NewSimulator() *Simulator {- s := &Simulator{}- s.initPatterns()- return s-}--// Simulate returns a simulated result for a command without executing it.-func (s *Simulator) Simulate(command string) SimulationResult {- for _, pattern := range s.patterns {- if matches := pattern.match.FindStringSubmatch(command); matches != nil {- result := pattern.generate(command, matches)- result.Simulated = true- return result- }- }-- // Default simulation for unknown commands- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would execute: %s", command),- ExitCode: 0,- WouldDo: "Execute unknown command",- Reversible: false,- Simulated: true,- }-}--func (s *Simulator) initPatterns() {- s.patterns = []simulationPattern{- // systemctl operations- {- match: regexp.MustCompile(`(?i)systemctl\s+(restart|stop|start)\s+(\S+)`),- generate: func(cmd string, matches []string) SimulationResult {- action := matches[1]- service := matches[2]- return SimulationResult{- Output: fmt.Sprintf(`[SIMULATED] %s.service - %s Service- Loaded: loaded (/lib/systemd/system/%s.service; enabled)- Active: active (running)--Would %s service %s`, service, strings.Title(service), service, action, service),- ExitCode: 0,- WouldDo: fmt.Sprintf("%s service %s", strings.Title(action), service),- Reversible: true,- RollbackCmd: fmt.Sprintf("systemctl %s %s", reverseAction(action), service),- }- },- },- // apt update- {- match: regexp.MustCompile(`(?i)apt\s+update`),- generate: func(cmd string, matches []string) SimulationResult {- return SimulationResult{- Output: `[SIMULATED] Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease-Hit:2 http://archive.ubuntu.com/ubuntu jammy-updates InRelease-Hit:3 http://archive.ubuntu.com/ubuntu jammy-security InRelease-Reading package lists... Done-Building dependency tree... Done-42 packages can be upgraded. Run 'apt list --upgradable' to see them.`,- ExitCode: 0,- WouldDo: "Update package lists from repositories",- Reversible: false, // Can't un-update- RollbackCmd: "",- }- },- },- // apt upgrade- {- match: regexp.MustCompile(`(?i)apt\s+(upgrade|dist-upgrade|full-upgrade)`),- generate: func(cmd string, matches []string) SimulationResult {- return SimulationResult{- Output: `[SIMULATED] Reading package lists... Done-Building dependency tree... Done-Calculating upgrade... Done-The following packages will be upgraded:- base-files curl libcurl4 nginx openssh-client openssh-server- openssl libssl3 vim vim-common vim-runtime-11 upgraded, 0 newly installed, 0 to remove.-Need to get 15.2 MB of archives.-After this operation, 128 kB of additional disk space will be used.--Would upgrade 11 packages`,- ExitCode: 0,- WouldDo: "Upgrade 11 packages (base-files, curl, nginx, openssh, etc.)",- Reversible: false, // Package upgrades are hard to reverse- RollbackCmd: "",- }- },- },- // apt install- {- match: regexp.MustCompile(`(?i)apt\s+install\s+(.+)`),- generate: func(cmd string, matches []string) SimulationResult {- packages := matches[1]- return SimulationResult{- Output: fmt.Sprintf(`[SIMULATED] Reading package lists... Done-Building dependency tree... Done-The following NEW packages will be installed:- %s-0 upgraded, 1 newly installed, 0 to remove.-Need to get 2.4 MB of archives.--Would install: %s`, packages, packages),- ExitCode: 0,- WouldDo: fmt.Sprintf("Install package(s): %s", packages),- Reversible: true,- RollbackCmd: fmt.Sprintf("apt remove %s", packages),- }- },- },- // apt remove- {- match: regexp.MustCompile(`(?i)apt\s+(remove|purge)\s+(.+)`),- generate: func(cmd string, matches []string) SimulationResult {- action := matches[1]- packages := matches[2]- return SimulationResult{- Output: fmt.Sprintf(`[SIMULATED] Reading package lists... Done-Building dependency tree... Done-The following packages will be REMOVED:- %s-0 upgraded, 0 newly installed, 1 to remove.-After this operation, 5.2 MB disk space will be freed.--Would %s: %s`, packages, action, packages),- ExitCode: 0,- WouldDo: fmt.Sprintf("Remove package(s): %s", packages),- Reversible: true,- RollbackCmd: fmt.Sprintf("apt install %s", packages),- }- },- },- // docker restart/stop/start- {- match: regexp.MustCompile(`(?i)docker\s+(restart|stop|start)\s+(\S+)`),- generate: func(cmd string, matches []string) SimulationResult {- action := matches[1]- container := matches[2]- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] %s\nWould %s container %s", container, action, container),- ExitCode: 0,- WouldDo: fmt.Sprintf("%s container %s", strings.Title(action), container),- Reversible: true,- RollbackCmd: fmt.Sprintf("docker %s %s", reverseAction(action), container),- }- },- },- // docker exec- {- match: regexp.MustCompile(`(?i)docker\s+exec\s+(?:-it?\s+)?(\S+)\s+(.+)`),- generate: func(cmd string, matches []string) SimulationResult {- container := matches[1]- execCmd := matches[2]- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would execute in container %s: %s", container, execCmd),- ExitCode: 0,- WouldDo: fmt.Sprintf("Execute command in container %s", container),- Reversible: false,- RollbackCmd: "",- }- },- },- // pct operations (Proxmox containers)- {- match: regexp.MustCompile(`(?i)pct\s+(start|stop|reboot)\s+(\d+)`),- generate: func(cmd string, matches []string) SimulationResult {- action := matches[1]- vmid := matches[2]- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would %s container %s", action, vmid),- ExitCode: 0,- WouldDo: fmt.Sprintf("%s LXC container %s", strings.Title(action), vmid),- Reversible: true,- RollbackCmd: fmt.Sprintf("pct %s %s", reverseAction(action), vmid),- }- },- },- // pct resize- {- match: regexp.MustCompile(`(?i)pct\s+resize\s+(\d+)\s+(\S+)\s+([+-]?\d+[KMGT]?)`),- generate: func(cmd string, matches []string) SimulationResult {- vmid := matches[1]- disk := matches[2]- size := matches[3]- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would resize container %s disk %s by %s", vmid, disk, size),- ExitCode: 0,- WouldDo: fmt.Sprintf("Resize container %s disk %s by %s", vmid, disk, size),- Reversible: strings.HasPrefix(size, "+"), // Only growth is "reversible" (shrink back)- RollbackCmd: "", // Disk resize is complex to reverse- }- },- },- // qm operations (Proxmox VMs)- {- match: regexp.MustCompile(`(?i)qm\s+(start|stop|reboot|shutdown)\s+(\d+)`),- generate: func(cmd string, matches []string) SimulationResult {- action := matches[1]- vmid := matches[2]- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would %s VM %s", action, vmid),- ExitCode: 0,- WouldDo: fmt.Sprintf("%s VM %s", strings.Title(action), vmid),- Reversible: true,- RollbackCmd: fmt.Sprintf("qm %s %s", reverseAction(action), vmid),- }- },- },- // kill process- {- match: regexp.MustCompile(`(?i)kill\s+(-\d+\s+)?(\d+)`),- generate: func(cmd string, matches []string) SimulationResult {- signal := strings.TrimSpace(matches[1])- pid := matches[2]- if signal == "" {- signal = "-15"- }- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would send signal %s to process %s", signal, pid),- ExitCode: 0,- WouldDo: fmt.Sprintf("Send signal %s to process %s", signal, pid),- Reversible: false,- RollbackCmd: "",- }- },- },- // pkill- {- match: regexp.MustCompile(`(?i)pkill\s+(?:-\d+\s+)?(\S+)`),- generate: func(cmd string, matches []string) SimulationResult {- process := matches[1]- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would kill processes matching: %s", process),- ExitCode: 0,- WouldDo: fmt.Sprintf("Kill processes matching '%s'", process),- Reversible: false,- RollbackCmd: "",- }- },- },- // rm files- {- match: regexp.MustCompile(`(?i)rm\s+(-[rf]+\s+)?(.+)`),- generate: func(cmd string, matches []string) SimulationResult {- flags := strings.TrimSpace(matches[1])- path := matches[2]- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would remove: %s (flags: %s)", path, flags),- ExitCode: 0,- WouldDo: fmt.Sprintf("Remove %s", path),- Reversible: false, // File deletion is not reversible- RollbackCmd: "",- }- },- },- // chmod- {- match: regexp.MustCompile(`(?i)chmod\s+(-R\s+)?(\d+|[ugoa][+-=][rwx]+)\s+(.+)`),- generate: func(cmd string, matches []string) SimulationResult {- recursive := matches[1] != ""- mode := matches[2]- path := matches[3]- desc := fmt.Sprintf("Change permissions of %s to %s", path, mode)- if recursive {- desc += " (recursive)"- }- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would %s", strings.ToLower(desc)),- ExitCode: 0,- WouldDo: desc,- Reversible: false, // Would need to record old permissions- RollbackCmd: "",- }- },- },- // chown- {- match: regexp.MustCompile(`(?i)chown\s+(-R\s+)?(\S+)\s+(.+)`),- generate: func(cmd string, matches []string) SimulationResult {- recursive := matches[1] != ""- owner := matches[2]- path := matches[3]- desc := fmt.Sprintf("Change owner of %s to %s", path, owner)- if recursive {- desc += " (recursive)"- }- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would %s", strings.ToLower(desc)),- ExitCode: 0,- WouldDo: desc,- Reversible: false,- RollbackCmd: "",- }- },- },- // nginx reload/restart- {- match: regexp.MustCompile(`(?i)nginx\s+(-s\s+)?(reload|restart|stop|start)`),- generate: func(cmd string, matches []string) SimulationResult {- action := matches[2]- return SimulationResult{- Output: fmt.Sprintf("[SIMULATED] Would %s nginx", action),- ExitCode: 0,- WouldDo: fmt.Sprintf("%s nginx", strings.Title(action)),- Reversible: true,- RollbackCmd: fmt.Sprintf("nginx -s %s", reverseAction(action)),- }- },- },- // df (disk free) - diagnostic- {- match: regexp.MustCompile(`(?i)^df\b`),- generate: func(cmd string, matches []string) SimulationResult {- return SimulationResult{- Output: `[SIMULATED] Filesystem Size Used Avail Use% Mounted on-/dev/sda1 100G 45G 55G 45% /-/dev/sdb1 500G 200G 300G 40% /data-tmpfs 16G 1.2G 15G 8% /dev/shm`,- ExitCode: 0,- WouldDo: "Display disk space usage",- Reversible: true, // Read-only- RollbackCmd: "",- }- },- },- // free (memory) - diagnostic- {- match: regexp.MustCompile(`(?i)^free\b`),- generate: func(cmd string, matches []string) SimulationResult {- return SimulationResult{- Output: `[SIMULATED] total used free shared buff/cache available-Mem: 32768000 12500000 8200000 512000 12068000 19200000-Swap: 8192000 100000 8092000`,- ExitCode: 0,- WouldDo: "Display memory usage",- Reversible: true, // Read-only- RollbackCmd: "",- }- },- },- // journalctl - diagnostic- {- match: regexp.MustCompile(`(?i)^journalctl\b`),- generate: func(cmd string, matches []string) SimulationResult {- return SimulationResult{- Output: `[SIMULATED] -- Logs begin at Mon 2024-01-01 00:00:00 UTC, end at now. ---Jan 11 10:00:00 server systemd[1]: Started Session 1 of user admin.-Jan 11 10:00:01 server nginx[1234]: 10.0.0.1 - - [11/Jan/2024:10:00:01 +0000] "GET / HTTP/1.1" 200-Jan 11 10:00:02 server sshd[5678]: Accepted publickey for admin from 10.0.0.2`,- ExitCode: 0,- WouldDo: "Display system logs",- Reversible: true, // Read-only- RollbackCmd: "",- }- },- },- }-}--// reverseAction returns the opposite action for rollback.-func reverseAction(action string) string {- action = strings.ToLower(action)- switch action {- case "start":- return "stop"- case "stop":- return "start"- case "restart":- return "restart" // Idempotent- case "reboot":- return "start"- case "reload":- return "reload"- default:- return action- }-}--// Global simulator instance-var defaultSimulator = NewSimulator()--// Simulate uses the default simulator to simulate a command.-func Simulate(command string) SimulationResult {- return defaultSimulator.Simulate(command)-}diff --git a/internal/ai/dryrun/simulator_test.go b/internal/ai/dryrun/simulator_test.godeleted file mode 100644index 3e350cf273..0000000000--- a/internal/ai/dryrun/simulator_test.go+++ /dev/null@@ -1,485 +0,0 @@-package dryrun--import (- "strings"- "testing"-)--func TestSimulator_Systemctl(t *testing.T) {- tests := []struct {- name string- command string- wantWouldDo string- wantReverse bool- wantRollback string- }{- {- name: "restart service",- command: "systemctl restart nginx",- wantWouldDo: "Restart service nginx",- wantReverse: true,- wantRollback: "systemctl restart nginx",- },- {- name: "stop service",- command: "systemctl stop apache2",- wantWouldDo: "Stop service apache2",- wantReverse: true,- wantRollback: "systemctl start apache2",- },- {- name: "start service",- command: "systemctl start mysql",- wantWouldDo: "Start service mysql",- wantReverse: true,- wantRollback: "systemctl stop mysql",- },- }-- sim := NewSimulator()-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := sim.Simulate(tt.command)-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if !strings.Contains(result.WouldDo, tt.wantWouldDo) {- t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)- }-- if result.Reversible != tt.wantReverse {- t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)- }-- if tt.wantRollback != "" && result.RollbackCmd != tt.wantRollback {- t.Errorf("Simulate() RollbackCmd = %q, want %q", result.RollbackCmd, tt.wantRollback)- }-- if result.ExitCode != 0 {- t.Errorf("Simulate() ExitCode = %v, want 0", result.ExitCode)- }-- if !strings.Contains(result.Output, "[SIMULATED]") {- t.Errorf("Simulate() Output should contain [SIMULATED]")- }- })- }-}--func TestSimulator_Apt(t *testing.T) {- tests := []struct {- name string- command string- wantWouldDo string- wantReverse bool- }{- {- name: "apt update",- command: "apt update",- wantWouldDo: "Update package lists",- wantReverse: false,- },- {- name: "apt upgrade",- command: "apt upgrade",- wantWouldDo: "Upgrade",- wantReverse: false,- },- {- name: "apt install",- command: "apt install htop vim",- wantWouldDo: "Install package",- wantReverse: true,- },- {- name: "apt remove",- command: "apt remove nginx",- wantWouldDo: "Remove package",- wantReverse: true,- },- }-- sim := NewSimulator()-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := sim.Simulate(tt.command)-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if !strings.Contains(result.WouldDo, tt.wantWouldDo) {- t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)- }-- if result.Reversible != tt.wantReverse {- t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)- }- })- }-}--func TestSimulator_Docker(t *testing.T) {- tests := []struct {- name string- command string- wantWouldDo string- wantReverse bool- }{- {- name: "docker restart",- command: "docker restart myapp",- wantWouldDo: "Restart container myapp",- wantReverse: true,- },- {- name: "docker stop",- command: "docker stop webserver",- wantWouldDo: "Stop container webserver",- wantReverse: true,- },- {- name: "docker exec",- command: "docker exec -it nginx bash",- wantWouldDo: "Execute command in container",- wantReverse: false,- },- }-- sim := NewSimulator()-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := sim.Simulate(tt.command)-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if !strings.Contains(result.WouldDo, tt.wantWouldDo) {- t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)- }-- if result.Reversible != tt.wantReverse {- t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)- }- })- }-}--func TestSimulator_Proxmox(t *testing.T) {- tests := []struct {- name string- command string- wantWouldDo string- wantReverse bool- }{- {- name: "pct start container",- command: "pct start 100",- wantWouldDo: "Start LXC container 100",- wantReverse: true,- },- {- name: "pct stop container",- command: "pct stop 101",- wantWouldDo: "Stop LXC container 101",- wantReverse: true,- },- {- name: "qm start VM",- command: "qm start 200",- wantWouldDo: "Start VM 200",- wantReverse: true,- },- {- name: "qm shutdown VM",- command: "qm shutdown 201",- wantWouldDo: "Shutdown VM 201",- wantReverse: true,- },- {- name: "pct resize",- command: "pct resize 100 rootfs +10G",- wantWouldDo: "Resize container 100",- wantReverse: true, // Growth is "reversible" in the sense we can shrink- },- }-- sim := NewSimulator()-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := sim.Simulate(tt.command)-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if !strings.Contains(result.WouldDo, tt.wantWouldDo) {- t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)- }-- if result.Reversible != tt.wantReverse {- t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)- }- })- }-}--func TestSimulator_ProcessManagement(t *testing.T) {- tests := []struct {- name string- command string- wantWouldDo string- wantReverse bool- }{- {- name: "kill process",- command: "kill 12345",- wantWouldDo: "Send signal",- wantReverse: false,- },- {- name: "kill with signal",- command: "kill -9 12345",- wantWouldDo: "Send signal -9",- wantReverse: false,- },- {- name: "pkill process",- command: "pkill nginx",- wantWouldDo: "Kill processes matching 'nginx'",- wantReverse: false,- },- }-- sim := NewSimulator()-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := sim.Simulate(tt.command)-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if !strings.Contains(result.WouldDo, tt.wantWouldDo) {- t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)- }-- if result.Reversible != tt.wantReverse {- t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)- }- })- }-}--func TestSimulator_FileOperations(t *testing.T) {- tests := []struct {- name string- command string- wantWouldDo string- wantReverse bool- }{- {- name: "rm file",- command: "rm /tmp/test.log",- wantWouldDo: "Remove",- wantReverse: false,- },- {- name: "rm recursive",- command: "rm -rf /tmp/data",- wantWouldDo: "Remove",- wantReverse: false,- },- {- name: "chmod",- command: "chmod 755 /usr/local/bin/script.sh",- wantWouldDo: "Change permissions",- wantReverse: false,- },- {- name: "chown",- command: "chown www-data:www-data /var/www",- wantWouldDo: "Change owner",- wantReverse: false,- },- }-- sim := NewSimulator()-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := sim.Simulate(tt.command)-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if !strings.Contains(result.WouldDo, tt.wantWouldDo) {- t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)- }-- if result.Reversible != tt.wantReverse {- t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)- }- })- }-}--func TestSimulator_Diagnostics(t *testing.T) {- tests := []struct {- name string- command string- wantWouldDo string- wantReverse bool- }{- {- name: "df disk free",- command: "df -h",- wantWouldDo: "Display disk space",- wantReverse: true, // Read-only- },- {- name: "free memory",- command: "free -m",- wantWouldDo: "Display memory usage",- wantReverse: true, // Read-only- },- {- name: "journalctl",- command: "journalctl -u nginx -n 100",- wantWouldDo: "Display system logs",- wantReverse: true, // Read-only- },- }-- sim := NewSimulator()-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := sim.Simulate(tt.command)-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if !strings.Contains(result.WouldDo, tt.wantWouldDo) {- t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)- }-- if result.Reversible != tt.wantReverse {- t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)- }- })- }-}--func TestSimulator_Nginx(t *testing.T) {- tests := []struct {- name string- command string- wantWouldDo string- wantReverse bool- }{- {- name: "nginx reload",- command: "nginx -s reload",- wantWouldDo: "Reload nginx",- wantReverse: true,- },- {- name: "nginx restart",- command: "nginx -s restart",- wantWouldDo: "Restart nginx",- wantReverse: true,- },- }-- sim := NewSimulator()-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- result := sim.Simulate(tt.command)-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if !strings.Contains(result.WouldDo, tt.wantWouldDo) {- t.Errorf("Simulate() WouldDo = %q, want to contain %q", result.WouldDo, tt.wantWouldDo)- }-- if result.Reversible != tt.wantReverse {- t.Errorf("Simulate() Reversible = %v, want %v", result.Reversible, tt.wantReverse)- }- })- }-}--func TestSimulator_UnknownCommand(t *testing.T) {- sim := NewSimulator()-- result := sim.Simulate("some-unknown-command --arg1 --arg2")-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if result.WouldDo != "Execute unknown command" {- t.Errorf("Simulate() WouldDo = %q, want %q", result.WouldDo, "Execute unknown command")- }-- if result.Reversible {- t.Error("Simulate() unknown command should not be reversible")- }-- if !strings.Contains(result.Output, "[SIMULATED]") {- t.Error("Simulate() Output should contain [SIMULATED]")- }-- if !strings.Contains(result.Output, "some-unknown-command") {- t.Error("Simulate() Output should contain the original command")- }-}--func TestGlobalSimulate(t *testing.T) {- result := Simulate("systemctl restart nginx")-- if !result.Simulated {- t.Error("Simulate() Simulated = false, want true")- }-- if !strings.Contains(result.WouldDo, "Restart") {- t.Errorf("Simulate() WouldDo = %q, want to contain 'Restart'", result.WouldDo)- }-}--func TestReverseAction(t *testing.T) {- tests := []struct {- action string- want string- }{- {"start", "stop"},- {"stop", "start"},- {"restart", "restart"},- {"reboot", "start"},- {"reload", "reload"},- {"unknown", "unknown"},- }-- for _, tt := range tests {- t.Run(tt.action, func(t *testing.T) {- got := reverseAction(tt.action)- if got != tt.want {- t.Errorf("reverseAction(%q) = %q, want %q", tt.action, got, tt.want)- }- })- }-}