Phase 3: Plugin-UI-System (WordPress-Style)

Backend:
- PluginManifest um 5 neue UI-Felder erweitert: menu_items, page_routes,
  detail_tabs, settings_pages, dashboard_widgets (FrontendMenuItem,
  FrontendPageRoute, FrontendDetailTab, FrontendSettingsPage,
  FrontendDashboardWidget)
- GET /api/v1/plugins/active-manifests Endpoint liefert UI-Manifeste
  aller aktiven Plugins
- Registry.get_active_manifests() + PluginService.get_active_manifests()
- 12 Built-in Plugins mit UI-Manifest-Daten gefuellt (menu_items,
  page_routes, detail_tabs, settings_pages)
- Plugin-Install-System: POST /upload (ZIP), POST /install-url (URL)
  mit Validierung (Manifest, dangerous imports, SQL migrations)

Frontend:
- pluginStore.ts (Zustand) mit PluginUiManifest Typen + Selektoren
- useActivePluginManifests() React Query Hook
- PluginRegistry.tsx — fetcht Manifeste beim App-Start
- PluginLoader.tsx — dynamisches React.lazy() mit ErrorBoundary
- PluginRouteRenderer.tsx — Catch-all fuer Plugin-Routes
- routes/index.tsx — Catch-all Routes fuer Plugin-Pages + Settings
- Sidebar.tsx — dynamische Plugin Menu-Items mit Grouping + Icons
- Settings.tsx — dynamische Plugin Settings-Pages
- ContactDetail.tsx — dynamische Plugin Detail-Tabs mit Permissions
- AppShell.tsx — PluginRegistry Provider eingebunden
- SettingsPlugins.tsx — Install-UI (ZIP Upload + URL Install)
- plugins.ts — useUploadPlugin() + useInstallPluginFromUrl() Hooks

Docs & Templates:
- docs/plugin-development-guide.md — komplette Entwickler-Doku
- templates/plugin-template/ — Boilerplate mit allen Manifest-Feldern

Tests:
- 34 Vitest-Tests (PluginRegistry, PluginLoader, PluginRouteRenderer,
  pluginStore) — alle bestanden
- TSC: keine neuen Errors (nur pre-existing Dms.tsx)
This commit is contained in:
Agent Zero
2026-07-23 19:01:18 +02:00
parent 4f70c1d912
commit fc96a2f86c
43 changed files with 3005 additions and 204 deletions
@@ -8,7 +8,11 @@ import { Input } from '@/components/ui/Input';
import { useToast } from '@/components/ui/Toast';
import { Loader2 } from 'lucide-react';
import * as LucideIcons from 'lucide-react';
import { HistoryViewer } from '@/components/HistoryViewer';
import { usePluginStore } from '@/store/pluginStore';
import { PluginPage } from '@/components/plugins/PluginLoader';
import { useAuthStore } from '@/store/authStore';
import {
type UnifiedContact,
type ContactPerson,
@@ -135,6 +139,11 @@ function ContactPersonModal({
);
}
function getIcon(name: string): React.ReactNode {
const Icon = (LucideIcons as any)[name];
return Icon ? <Icon className="h-4 w-4" /> : <LucideIcons.FileText className="h-4 w-4" />;
}
export function ContactDetail({ contact, loading, onEdit, onDeleted }: ContactDetailProps) {
const { t } = useTranslation();
const toast = useToast();
@@ -144,6 +153,9 @@ export function ContactDetail({ contact, loading, onEdit, onDeleted }: ContactDe
const deletePersonMutation = useDeleteContactPerson();
const [personModalOpen, setPersonModalOpen] = useState(false);
const [editingPerson, setEditingPerson] = useState<ContactPerson | null>(null);
const [activeTab, setActiveTab] = useState('details');
const pluginTabs = usePluginStore(s => s.getDetailTabsForEntity('contact'));
const user = useAuthStore(s => s.user);
if (loading) {
return (
@@ -203,6 +215,21 @@ export function ContactDetail({ contact, loading, onEdit, onDeleted }: ContactDe
}
};
const visiblePluginTabs = pluginTabs.filter(tab => {
if (!tab.permission) return true;
return user?.permissions?.includes(tab.permission) ?? false;
});
const allTabs = [
{ id: 'details', label: t('contacts.details', 'Details'), icon: null },
...visiblePluginTabs.map(tab => ({
id: tab.component,
label: t(tab.label_key, tab.label),
icon: tab.icon,
component: tab.component,
})),
];
return (
<div className="overflow-y-auto h-full" data-testid="contact-detail">
{/* Header */}
@@ -224,7 +251,28 @@ export function ContactDetail({ contact, loading, onEdit, onDeleted }: ContactDe
</div>
</div>
<div className="p-4">
{/* Tab Bar */}
<div className="flex border-b border-secondary-200 bg-white sticky top-[58px] z-10 overflow-x-auto" role="tablist">
{allTabs.map(tab => (
<button
key={tab.id}
role="tab"
aria-selected={activeTab === tab.id}
className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${
activeTab === tab.id
? 'border-primary-500 text-primary-700'
: 'border-transparent text-secondary-500 hover:text-secondary-700 hover:border-secondary-300'
}`}
onClick={() => setActiveTab(tab.id)}
>
{tab.icon && getIcon(tab.icon)}
{tab.label}
</button>
))}
</div>
{activeTab === 'details' ? (
<div className="p-4">
{/* Contact Persons */}
<Section
title={t('contacts.contactPersons')}
@@ -367,6 +415,19 @@ export function ContactDetail({ contact, loading, onEdit, onDeleted }: ContactDe
</Section>
)}
</div>
) : (
<div className="p-4">
{allTabs.filter((t): t is { id: string; label: string; icon: string; component: string } => t.id !== 'details').map(tab => (
activeTab === tab.id && (
<PluginPage
key={tab.id}
component={tab.component}
pluginName={tab.label}
/>
)
))}
</div>
)}
<ContactPersonModal
open={personModalOpen}
@@ -6,6 +6,7 @@ import { PluginToolbar } from './PluginToolbar';
import { MessageSidebar } from './MessageSidebar';
import { ToastContainer } from '@/components/ui/Toast';
import { useAIContext } from '@/hooks/useAIContext';
import { PluginRegistry } from '@/components/plugins/PluginRegistry';
export function AppShell() {
const location = useLocation();
@@ -18,6 +19,7 @@ export function AppShell() {
return (
<div className="flex h-screen overflow-hidden bg-secondary-50" data-testid="app-shell">
<PluginRegistry />
<Sidebar />
<div className="flex-1 flex flex-col overflow-hidden">
<TopBar />
+106
View File
@@ -4,6 +4,8 @@ import { NavLink, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useUIStore } from '@/store/uiStore';
import { Calendar, ChevronRight, FileText, Home, Mail, Monitor, Users } from 'lucide-react';
import { usePluginStore } from '@/store/pluginStore';
import * as LucideIcons from 'lucide-react';
interface NavLeaf {
to: string;
@@ -26,6 +28,11 @@ 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 = (LucideIcons as any)[name];
return Icon ? <Icon className="h-4 w-4" /> : <LucideIcons.FileText className="h-4 w-4" />;
}
const singleItems: NavSingleItem[] = [
{ to: '/dashboard', labelKey: 'nav.dashboard', icon: <Home className="w-5 h-5 flex-shrink-0" aria-hidden="true" strokeWidth={2} /> },
{ to: '/contacts', labelKey: 'nav.contacts', icon: <Users className="w-5 h-5 flex-shrink-0" aria-hidden="true" strokeWidth={2} /> },
@@ -66,6 +73,7 @@ export function Sidebar() {
const { t } = useTranslation();
const { sidebarOpen, setSidebarOpen } = useUIStore();
const location = useLocation();
const pluginMenuItems = usePluginStore(s => s.getAllMenuItems());
const initialExpanded = treeItems
.filter((item) => item.children.some((child) => location.pathname.startsWith(child.to)))
@@ -196,6 +204,104 @@ export function Sidebar() {
);
})}
{pluginMenuItems.length > 0 && (
<>
<li className="px-3 pt-4 pb-1">
<span className="text-xs font-semibold uppercase tracking-wider text-secondary-500">
{t('nav.plugins', 'Plugins')}
</span>
</li>
{(() => {
const groups = new Map<string, typeof pluginMenuItems>();
const singles: typeof pluginMenuItems = [];
for (const item of pluginMenuItems) {
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) {
elements.push(
<li key={item.path}>
<NavLink
to={item.path}
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.label_key, item.label)}
>
{getIcon(item.icon)}
<span className="truncate">{t(item.label_key, item.label)}</span>
</NavLink>
</li>
);
}
for (const [group, items] of 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(items[0].icon)}
<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">
{items.map((child) => (
<li key={child.path}>
<NavLink
to={child.path}
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.label_key, child.label)}
>
<span className="truncate">{t(child.label_key, child.label)}</span>
</NavLink>
</li>
))}
</ul>
)}
</li>
);
}
return elements;
})()}
</>
)}
{bottomItems.map((item) => (
<li key={item.to}>
<NavLink
@@ -0,0 +1,84 @@
import React, { Suspense, lazy, Component, ReactNode } from 'react';
import { Loader2 } from 'lucide-react';
// ── Error Boundary ──────────────────────────────────────────────────────
interface PluginErrorBoundaryProps {
children: ReactNode;
pluginName: string;
}
interface PluginErrorBoundaryState {
hasError: boolean;
}
class PluginErrorBoundary extends Component<PluginErrorBoundaryProps, PluginErrorBoundaryState> {
state = { hasError: false };
static getDerivedStateFromError(): PluginErrorBoundaryState {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return (
<div className="p-4 text-sm text-red-600" role="alert">
Failed to load plugin: {this.props.pluginName}
</div>
);
}
return this.props.children;
}
}
// ── Lazy Component Cache ────────────────────────────────────────────────
const componentCache = new Map<string, React.LazyExoticComponent<React.ComponentType<any>>>();
function getLazyComponent(componentPath: string): React.LazyExoticComponent<React.ComponentType<any>> {
if (componentCache.has(componentPath)) {
return componentCache.get(componentPath)!;
}
// Convert @/pages/Mail to ../pages/Mail for dynamic import
const importPath = componentPath.replace(/^@\//, '../');
const LazyComp = lazy(() =>
import(/* @vite-ignore */ importPath).then((m) => ({
default: m.default || m[Object.keys(m)[0]],
}))
);
componentCache.set(componentPath, LazyComp);
return LazyComp;
}
// ── PluginPage Component ───────────────────────────────────────────────
interface PluginPageProps {
component: string;
pluginName: string;
}
/**
* PluginPage — dynamically loads a plugin page component using React.lazy().
* Wraps the lazy component in Suspense with a centered spinner fallback
* and an ErrorBoundary that shows a fallback message on failure.
*/
export function PluginPage({ component, pluginName }: PluginPageProps) {
const LazyComp = getLazyComponent(component);
return (
<PluginErrorBoundary pluginName={pluginName}>
<Suspense
fallback={
<div className="flex items-center justify-center min-h-[50vh]">
<Loader2 className="animate-spin h-8 w-8 text-primary-500" />
</div>
}
>
<LazyComp />
</Suspense>
</PluginErrorBoundary>
);
}
@@ -0,0 +1,35 @@
import { useEffect } from 'react';
import { useActivePluginManifests } from '@/api/pluginManifests';
import { usePluginStore } from '@/store/pluginStore';
/**
* PluginRegistry — invisible provider component that fetches active plugin
* UI manifests on mount and populates the plugin store.
*
* Must be placed inside AppShell or at the root of the protected route tree.
*/
export function PluginRegistry() {
const { data, isLoading, error } = useActivePluginManifests();
const setManifests = usePluginStore((s) => s.setManifests);
const setLoading = usePluginStore((s) => s.setLoading);
const setError = usePluginStore((s) => s.setError);
useEffect(() => {
setLoading(isLoading);
}, [isLoading, setLoading]);
useEffect(() => {
if (data?.plugins) {
setManifests(data.plugins);
}
}, [data, setManifests]);
useEffect(() => {
if (error) {
setError(error instanceof Error ? error.message : 'Failed to load plugin manifests');
}
}, [error, setError]);
// This component renders nothing visible
return null;
}
@@ -0,0 +1,62 @@
import { useLocation } from 'react-router-dom';
import { usePluginStore } from '@/store/pluginStore';
import { PluginPage } from './PluginLoader';
/**
* PluginRouteRenderer — catch-all route handler that checks the current URL
* against all plugin page_routes from the plugin store.
*
* If a matching route is found, it renders the plugin's page component.
* Otherwise it renders a simple "Not Found" message.
*
* This component is intended to be used as the last child of the protected
* route group in routes/index.tsx:
* { path: '*', element: <PluginRouteRenderer /> }
*/
export function PluginRouteRenderer() {
const location = useLocation();
const getAllPageRoutes = usePluginStore((s) => s.getAllPageRoutes);
const loaded = usePluginStore((s) => s.loaded);
const routes = getAllPageRoutes();
// Find the first matching route (exact match or prefix match for nested routes)
const matchedRoute = routes.find((r) => {
// Exact match
if (location.pathname === r.path) return true;
// Prefix match for nested routes (e.g. /calendar/settings matches /calendar)
if (r.path !== '/' && location.pathname.startsWith(r.path + '/')) return true;
return false;
});
if (matchedRoute) {
// Find the plugin name for display
const manifests = usePluginStore.getState().manifests;
const plugin = manifests.find((m) =>
m.page_routes.some((pr) => pr.path === matchedRoute.path)
);
const pluginName = plugin?.display_name || plugin?.name || matchedRoute.path;
return (
<PluginPage
component={matchedRoute.component}
pluginName={pluginName}
/>
);
}
// If manifests haven't loaded yet, show nothing (the static router handles it)
if (!loaded) {
return null;
}
// No plugin route matched — show a simple not-found
return (
<div className="flex flex-col items-center justify-center min-h-[50vh] text-secondary-500">
<h2 className="text-2xl font-semibold mb-2">Page Not Found</h2>
<p className="text-sm">
The page <code className="bg-secondary-100 px-1 rounded">{location.pathname}</code> was not found.
</p>
</div>
);
}
@@ -0,0 +1,63 @@
import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
// We test the error boundary and component cache directly
// by importing the module internals
import { PluginPage } from '../PluginLoader';
// The PluginErrorBoundary is not exported, so we test through PluginPage
// The componentCache is module-level and persists across tests
describe('PluginPage', () => {
it('shows error fallback when component fails to load', async () => {
// Use a non-existent component path - the dynamic import will fail
render(<PluginPage component="@/pages/NonExistentPage" pluginName="broken" />);
// The error boundary should catch the import error and show fallback
const errorMsg = await screen.findByText(/Failed to load plugin/);
expect(errorMsg).toBeInTheDocument();
expect(errorMsg).toHaveTextContent('broken');
});
it('shows error fallback with correct plugin name', async () => {
render(<PluginPage component="@/pages/AnotherMissingPage" pluginName="my_custom_plugin" />);
const errorMsg = await screen.findByText(/Failed to load plugin/);
expect(errorMsg).toHaveTextContent('my_custom_plugin');
});
it('error boundary catches import errors and shows fallback UI', async () => {
render(<PluginPage component="@/pages/NonExistentPage" pluginName="test" />);
// The error boundary should catch the failed dynamic import
const alert = await screen.findByRole('alert');
expect(alert).toBeInTheDocument();
expect(alert).toHaveTextContent('Failed to load plugin: test');
// Verify the error message has the correct CSS classes
expect(alert.className).toContain('text-red-600');
});
it('handles empty component path gracefully', async () => {
render(<PluginPage component="" pluginName="empty" />);
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('Failed to load plugin: empty');
});
it('error boundary has role="alert" for accessibility', async () => {
render(<PluginPage component="@/pages/MissingPage" pluginName="test" />);
const alert = await screen.findByRole('alert');
expect(alert).toBeInTheDocument();
expect(alert).toHaveTextContent('Failed to load plugin: test');
});
it('handles different plugin names in error boundary', async () => {
render(<PluginPage component="@/pages/YetAnotherMissing" pluginName="plugin_x" />);
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('plugin_x');
});
});
@@ -0,0 +1,78 @@
import React from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from '@testing-library/react';
import { PluginRegistry } from '../PluginRegistry';
import { usePluginStore } from '@/store/pluginStore';
import type { PluginUiManifest } from '@/store/pluginStore';
// Mock the API hook
const mockManifests: PluginUiManifest[] = [
{
name: 'test_plugin',
display_name: 'Test Plugin',
version: '1.0.0',
is_core: false,
menu_items: [
{ label_key: 'nav.test', label: 'Test', path: '/test', icon: 'TestTube', group: '', order: 100, badge_key: '' },
],
page_routes: [
{ path: '/test', component: '@/pages/Test', parent: '', protected: true, order: 100 },
],
detail_tabs: [],
settings_pages: [],
dashboard_widgets: [],
},
];
let mockQueryResult: any = {
data: { plugins: mockManifests, total: 1 },
isLoading: false,
error: null,
};
vi.mock('@/api/pluginManifests', () => ({
useActivePluginManifests: () => mockQueryResult,
}));
describe('PluginRegistry', () => {
beforeEach(() => {
usePluginStore.getState().reset();
mockQueryResult = {
data: { plugins: mockManifests, total: 1 },
isLoading: false,
error: null,
};
});
it('renders nothing visible', () => {
const { container } = render(<PluginRegistry />);
expect(container.innerHTML).toBe('');
});
it('populates store with manifests on mount', () => {
render(<PluginRegistry />);
const manifests = usePluginStore.getState().manifests;
expect(manifests).toHaveLength(1);
expect(manifests[0].name).toBe('test_plugin');
});
it('sets loading state while fetching', () => {
mockQueryResult = { data: null, isLoading: true, error: null };
render(<PluginRegistry />);
expect(usePluginStore.getState().loading).toBe(true);
});
it('sets error state on fetch failure', () => {
mockQueryResult = { data: null, isLoading: false, error: new Error('Network error') };
render(<PluginRegistry />);
expect(usePluginStore.getState().error).toBe('Network error');
});
it('handles empty manifests gracefully', () => {
mockQueryResult = { data: { plugins: [], total: 0 }, isLoading: false, error: null };
render(<PluginRegistry />);
const manifests = usePluginStore.getState().manifests;
expect(manifests).toHaveLength(0);
expect(usePluginStore.getState().loaded).toBe(true);
});
});
@@ -0,0 +1,120 @@
import React from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { PluginRouteRenderer } from '../PluginRouteRenderer';
import { usePluginStore } from '@/store/pluginStore';
import type { PluginUiManifest } from '@/store/pluginStore';
// Mock PluginPage to avoid lazy loading issues in tests
vi.mock('../PluginLoader', () => ({
PluginPage: ({ component, pluginName }: { component: string; pluginName: string }) => (
<div data-testid="plugin-page" data-component={component} data-plugin={pluginName}>
Plugin: {pluginName}
</div>
),
}));
const mockManifests: PluginUiManifest[] = [
{
name: 'mail_plugin',
display_name: 'Mail',
version: '1.0.0',
is_core: true,
menu_items: [],
page_routes: [
{ path: '/mail', component: '@/pages/Mail', parent: '', protected: true, order: 100 },
{ path: '/mail/settings', component: '@/pages/MailSettings', parent: '/mail', protected: true, order: 200 },
],
detail_tabs: [],
settings_pages: [],
dashboard_widgets: [],
},
{
name: 'calendar_plugin',
display_name: 'Calendar',
version: '1.0.0',
is_core: false,
menu_items: [],
page_routes: [
{ path: '/calendar', component: '@/pages/Calendar', parent: '', protected: true, order: 200 },
],
detail_tabs: [],
settings_pages: [],
dashboard_widgets: [],
},
];
describe('PluginRouteRenderer', () => {
beforeEach(() => {
usePluginStore.getState().reset();
});
it('renders plugin page for a matching route', () => {
usePluginStore.setState({
manifests: mockManifests,
loaded: true,
});
render(
<MemoryRouter initialEntries={['/mail']}>
<PluginRouteRenderer />
</MemoryRouter>
);
expect(screen.getByTestId('plugin-page')).toBeInTheDocument();
expect(screen.getByText('Plugin: Mail')).toBeInTheDocument();
});
it('renders plugin page for a nested route', () => {
usePluginStore.setState({
manifests: mockManifests,
loaded: true,
});
render(
<MemoryRouter initialEntries={['/mail/settings']}>
<PluginRouteRenderer />
</MemoryRouter>
);
expect(screen.getByTestId('plugin-page')).toBeInTheDocument();
expect(screen.getByText('Plugin: Mail')).toBeInTheDocument();
});
it('shows Not Found for unmatched URLs', () => {
usePluginStore.setState({
manifests: mockManifests,
loaded: true,
});
render(
<MemoryRouter initialEntries={['/unknown']}>
<PluginRouteRenderer />
</MemoryRouter>
);
expect(screen.getByText('Page Not Found')).toBeInTheDocument();
expect(screen.getByText(/unknown/)).toBeInTheDocument();
});
it('renders nothing when manifests have not loaded yet', () => {
usePluginStore.setState({
manifests: [],
loaded: false,
});
const { container } = render(
<MemoryRouter initialEntries={['/mail']}>
<PluginRouteRenderer />
</MemoryRouter>
);
expect(container.innerHTML).toBe('');
});
it('matches the first route when multiple match', () => {
usePluginStore.setState({
manifests: mockManifests,
loaded: true,
});
render(
<MemoryRouter initialEntries={['/calendar']}>
<PluginRouteRenderer />
</MemoryRouter>
);
expect(screen.getByText('Plugin: Calendar')).toBeInTheDocument();
});
});