Files
leocrm/frontend/src/components/layout/Sidebar.tsx
T
Agent Zero 24423b6802
Check Cross-Plugin Imports / check (push) Has been cancelled
feat(agent-memory): UI fuer Agent-Memories mit semantischer Suche — Modul 8/16
Drittes Modul via Phase-Q-Manifest-Architektur: Registrierung komplett
ueber das agent_memory-Plugin-Manifest (page_route /agent-memory +
menu_item, Brain-Icon) — routes/index.tsx unangetastet. Komponenten-Map
mit 40 Eintraegen.

Zusaetzlicher Fix: Sidebar-ICON_MAP um Brain, Store, Tags erweitert —
Marketplace (Store) und Tags zeigten bisher Fallback-Icons, weil die
Manifest-Icons nicht in der kuratierten Map standen.

Backend existierte vollstaendig (create mit Embedding, list mit
agent_id-Pflichtfilter + Typ + Pagination, semantische Suche via pgvector,
update mit Embedding-Regeneration, delete; agent_memory:read/write),
Frontend hatte 0% Abdeckung.

- api/agentMemory.ts: TanStack-Hooks (useAgentMemories mit
  enabled-Gating, useAgentMemorySearch, create/update/delete)
- pages/AgentMemory.tsx: Agent-Picker (Pflichtfeld — Backend filtert
  zwingend nach agent_id), Pick-Agent-Prompt, semantische Suche mit
  Relevanz-Score-Badges und Clear, Memory-Karten mit Typ-Badges
  (fact/context/pattern/instruction), Create/Edit-Dialog, Delete mit
  Confirm — Aktionen hinter agent_memory:write
- i18n agentMemory.* + nav.agentMemory de/en

Verifikation: Vitest 11/11 (Agent-Picker-Pflicht, Pick-Prompt, Badges,
Suche mit Score + Clear, Create/Edit prefilled, Delete mit+ohne Confirm,
Gating, Empty/Error) · tsc exit 0 · production build exit 0 ·
Backend-Regressionen (route-order, m5-miniapps) 10/10 · compileall
sauber · Manifest-Check OK.
2026-09-13 19:45:18 +02:00

339 lines
15 KiB
TypeScript

import React, { useState, useEffect, useMemo } from 'react';
import clsx from 'clsx';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useUIStore } from '@/store/uiStore';
import { ArrowLeft, ArrowRightLeft, Brain, CheckCircle2, ChevronRight, FileText, Home, Settings, Store, Tags, Users } from 'lucide-react';
import { usePluginStore } from '@/store/pluginStore';
// Curated icon map — avoids `import * as LucideIcons` which loads ALL icons and causes OOM in tests
import {
Bot, Sparkles, Workflow, ArrowUpDown, Copy, Tag, Activity,
Calendar, FolderOpen, Trash2, Link, MessageSquare, Mail,
Shield, UsersRound, BarChart3, Bell, Search, LogOut, Menu, X,
ChevronDown, User, Check, Plus, Edit, Filter, Star, Archive,
Reply, Forward, Paperclip, MoreVertical, RefreshCw, Download,
Upload, Eye, EyeOff, Lock, Unlock, Clock, AlertCircle,
CheckCircle, XCircle, Info, Loader2, Inbox, Send,
BookOpen, Lightbulb,
} from 'lucide-react';
const ICON_MAP: Record<string, React.ComponentType<{ className?: string }>> = {
Bot, Sparkles, Workflow, ArrowUpDown, Copy, Tag, Activity,
Calendar, FolderOpen, Trash2, Link, MessageSquare, Mail,
Shield, UsersRound, BarChart3, Bell, Settings, Users, Home,
FileText, Search, LogOut, Menu, X, ChevronDown, User, Check,
Plus, Edit, Filter, Star, Archive, Reply, Forward, Paperclip,
MoreVertical, RefreshCw, Download, Upload, Eye, EyeOff, Lock,
Unlock, Clock, AlertCircle, CheckCircle, XCircle, Info, Loader2,
Inbox, Send, ChevronRight, BookOpen, Lightbulb,
Brain, Store, Tags, ArrowRightLeft,
};
import { useMenuOrder } from '@/api/users';
import { usePermission } from '@/hooks/usePermission';
import { useWorkspace } from '@/hooks/useWorkspace';
import { useWorkspaceStore } from '@/store/workspaceStore';
import { useAuthStore } from '@/store/authStore';
interface NavSingleItem {
to: string;
labelKey: string;
icon: React.ReactNode;
order: number;
}
const chevronIcon = (expanded: boolean) => (
<ChevronRight className={clsx('w-4 h-4 flex-shrink-0 transition-transform duration-200', expanded ? 'rotate-90' : '')} aria-hidden="true" strokeWidth={2} />
);
function getIcon(name: string): React.ReactNode {
const Icon = ICON_MAP[name];
return Icon ? <Icon className="h-4 w-4" /> : <FileText className="h-4 w-4" />;
}
// Only non-plugin items: dashboard, system-dashboard.
// All other menu entries (contacts, calendar, dms, mail, ai-assistant, automation, reports, tasks, communication)
// are provided by plugin manifests via usePluginStore(s => s.getAllMenuItems()).
const singleItems: NavSingleItem[] = [
{ to: '/dashboard', labelKey: 'nav.dashboard', icon: <Home className="w-5 h-5 flex-shrink-0" aria-hidden="true" strokeWidth={2} />, order: 0 },
{ to: '/system-dashboard', labelKey: 'nav.systemDashboard', icon: <Activity className="w-5 h-5 flex-shrink-0" aria-hidden="true" strokeWidth={2} />, order: 90 },
{ to: '/approvals', labelKey: 'nav.approvals', icon: <CheckCircle2 className="w-5 h-5 flex-shrink-0" aria-hidden="true" strokeWidth={2} />, order: 91 },
{ to: '/delegations', labelKey: 'nav.delegations', icon: <ArrowRightLeft className="w-5 h-5 flex-shrink-0" aria-hidden="true" strokeWidth={2} />, order: 92 },
];
const bottomItems: NavSingleItem[] = [];
export function Sidebar() {
const navigate = useNavigate();
const { t } = useTranslation();
const { sidebarOpen, setSidebarOpen } = useUIStore();
const location = useLocation();
const manifests = usePluginStore(s => s.manifests);
const { data: menuOrderData } = useMenuOrder();
const { hasPermission } = usePermission();
const user = useAuthStore((state) => state.user);
const { isModuleVisible } = useWorkspace();
const moduleMenuOrder = useWorkspaceStore(s => s.moduleMenuOrder());
// Use hasPermission directly — permissions are loaded via useUserPermissions hook
const canAccess = (perm?: string): boolean => {
if (!perm) return true;
// While permissions are loading (undefined), show nothing for protected items
if (!user?.permissions && user?.is_system_admin === undefined) return false;
return hasPermission(perm);
};
const allMenuItems = useMemo(() => {
const staticItems = singleItems
// Backend enforces require_admin on system dashboard routes — hide the
// nav entry from non-admin users instead of showing a dead link.
.filter(item => item.to !== '/system-dashboard' || user?.is_system_admin)
.map(item => ({
path: item.to,
labelKey: item.labelKey,
label: item.labelKey,
icon: item.icon,
order: item.order,
group: undefined as string | undefined,
isStatic: true as const,
permission: item.to === '/dashboard' ? 'dashboard:read' : item.to === '/contacts' ? 'contacts:read' : undefined,
}));
const pluginItems = (manifests || [])
.flatMap((m) => (Array.isArray(m.menu_items) ? m.menu_items : []))
.filter((item): item is NonNullable<typeof item> => !!item && (!item.permission || canAccess(item.permission)))
.map(item => ({
path: item.path,
labelKey: item.label_key,
label: item.label,
icon: item.icon,
order: item.order,
group: item.group,
isStatic: false as const,
permission: item.permission,
}));
const allItems = [...staticItems, ...pluginItems];
// Filter by workspace visibility (in addition to permissions)
// If no workspace is active, isModuleVisible returns true (backward compatible)
const workspaceFiltered = allItems.filter(item => {
const moduleKey = item.path.replace(/^\//, '').split('/')[0];
return isModuleVisible(moduleKey);
});
// Apply saved menu order if available
const savedOrder = menuOrderData?.menu_order;
if (savedOrder && savedOrder.length > 0) {
const orderMap = new Map(savedOrder.map((id, idx) => [id, idx]));
return workspaceFiltered.sort((a, b) => {
// Map path to menu ID: static items use their path without leading /
const aId = a.path.startsWith('/') ? a.path.slice(1) : a.path;
const bId = b.path.startsWith('/') ? b.path.slice(1) : b.path;
const aIdx = orderMap.get(aId);
const bIdx = orderMap.get(bId);
if (aIdx !== undefined && bIdx !== undefined) return aIdx - bIdx;
if (aIdx !== undefined) return -1;
if (bIdx !== undefined) return 1;
// Fall back to order field for unknown items
if (a.order !== b.order) return a.order - b.order;
return a.label.localeCompare(b.label);
});
}
return workspaceFiltered.sort((a, b) => {
// N4: workspace menu_order is the admin-defined fallback order —
// the personal savedOrder above stays the user override.
const wsOrder = moduleMenuOrder;
const aWs = wsOrder.get(a.path.replace(/^\//, '').split('/')[0]);
const bWs = wsOrder.get(b.path.replace(/^\//, '').split('/')[0]);
if (aWs !== undefined && bWs !== undefined && aWs !== bWs) return aWs - bWs;
if (aWs !== undefined && bWs === undefined) return -1;
if (aWs === undefined && bWs !== undefined) return 1;
// Fall back to order field + label (backward compatible)
if (a.order !== b.order) return a.order - b.order;
return a.label.localeCompare(b.label);
});
}, [manifests, menuOrderData, user, isModuleVisible, moduleMenuOrder]);
const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set());
useEffect(() => {
setExpandedItems((prev) => {
const next = new Set(prev);
// Auto-expand groups whose child route is active
for (const item of allMenuItems) {
if (item.group && location.pathname.startsWith(item.path)) {
next.add(`plugin-group-${item.group}`);
}
}
return next;
});
}, [location.pathname, allMenuItems]);
const toggleExpand = (labelKey: string) => {
setExpandedItems((prev) => {
const next = new Set(prev);
if (next.has(labelKey)) next.delete(labelKey);
else next.add(labelKey);
return next;
});
};
return (
<>
{sidebarOpen && (
<div
className="fixed inset-0 bg-secondary-900/50 z-30 md:hidden"
onClick={() => setSidebarOpen(false)}
aria-hidden="true"
data-testid="sidebar-overlay"
/>
)}
<aside
className={clsx(
'fixed md:static inset-y-0 left-0 z-40 w-56 bg-secondary-900 text-secondary-300',
'flex flex-col transition-transform motion-safe:duration-300',
sidebarOpen ? 'translate-x-0' : '-translate-x-full md:hidden'
)}
aria-label="Seitenleiste Navigation"
data-testid="sidebar"
>
<div className="h-[58px] flex items-center gap-2 px-4 border-b border-secondary-700">
<button
onClick={() => navigate('/start')}
className="p-1.5 rounded-md text-secondary-400 hover:bg-secondary-700 hover:text-white flex items-center justify-center focus:outline-none"
aria-label="Zurück zur Startseite"
title="Zurück zur Startseite"
>
<ArrowLeft className="w-4 h-4" />
</button>
<span className="text-xl font-bold text-white">leocrm</span>
</div>
<nav className="flex-1 overflow-y-auto py-4" aria-label="Hauptnavigation">
<ul className="space-y-1 px-2">
{(() => {
const groups = new Map<string, typeof allMenuItems>();
const singles: typeof allMenuItems = [];
for (const item of allMenuItems) {
if (item.group) {
if (!groups.has(item.group)) groups.set(item.group, []);
groups.get(item.group)!.push(item);
} else {
singles.push(item);
}
}
const elements: React.ReactNode[] = [];
for (const item of singles) {
// Skip if user lacks permission
if (item.permission && !canAccess(item.permission)) continue;
// Skip admin-only items for non-admins
if (item.path === '/system-dashboard' && !user?.is_system_admin) continue;
elements.push(
<li key={item.path}>
<NavLink
to={item.path}
end
className={({ isActive }) =>
clsx(
'flex items-center gap-3 px-3 py-2.5 rounded-md text-sm font-medium min-h-touch',
'motion-safe:transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500',
isActive
? 'bg-primary-600 text-white'
: 'hover:bg-secondary-800 hover:text-white'
)
}
aria-label={t(item.labelKey)}
>
{item.isStatic ? item.icon : getIcon(item.icon as string)}
<span className="truncate">{t(item.labelKey, item.label)}</span>
</NavLink>
</li>
);
}
for (const [group, items] of groups) {
// Filter group items by permission
const visibleItems = items.filter(item => !item.permission || canAccess(item.permission));
if (visibleItems.length === 0) continue; // Hide empty groups
const groupKey = `plugin-group-${group}`;
const expanded = expandedItems.has(groupKey);
elements.push(
<li key={groupKey}>
<div
className={clsx(
'flex items-center gap-2 px-3 py-2.5 rounded-md text-sm font-medium min-h-touch',
'motion-safe:transition-colors cursor-pointer select-none',
'text-secondary-300 hover:bg-secondary-800 hover:text-white'
)}
onClick={() => toggleExpand(groupKey)}
role="button"
tabIndex={0}
aria-expanded={expanded}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleExpand(groupKey);
}
}}
>
{getIcon(visibleItems[0].icon as string)}
<span className="flex-1 truncate">{group}</span>
{chevronIcon(expanded)}
</div>
{expanded && (
<ul className="mt-1 ml-4 space-y-1 border-l border-secondary-700 pl-2" role="group">
{visibleItems.map((child) => (
<li key={child.path}>
<NavLink
to={child.path}
end
className={({ isActive }) =>
clsx(
'flex items-center gap-2 px-3 py-2 rounded-md text-sm min-h-touch',
'motion-safe:transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500',
isActive
? 'bg-primary-600 text-white font-medium'
: 'text-secondary-400 hover:bg-secondary-800 hover:text-white'
)
}
aria-label={t(child.labelKey, child.label)}
>
<span className="truncate">{t(child.labelKey, child.label)}</span>
</NavLink>
</li>
))}
</ul>
)}
</li>
);
}
return elements;
})()}
{bottomItems.map((item) => (
<li key={item.to}>
<NavLink
to={item.to}
end
className={({ isActive }) =>
clsx(
'flex items-center gap-3 px-3 py-2.5 rounded-md text-sm font-medium min-h-touch',
'motion-safe:transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500',
isActive
? 'bg-primary-600 text-white'
: 'hover:bg-secondary-800 hover:text-white'
)
}
aria-label={t(item.labelKey)}
>
{item.icon}
<span className="truncate">{t(item.labelKey)}</span>
</NavLink>
</li>
))}
</ul>
</nav>
</aside>
</>
);
}