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
@@ -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();
});
});