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
+15
View File
@@ -0,0 +1,15 @@
import { apiGet } from './client';
import { useQuery } from '@tanstack/react-query';
import type { PluginUiManifest } from '../store/pluginStore';
export function useActivePluginManifests() {
return useQuery({
queryKey: ['plugin-active-manifests'],
queryFn: async () => {
const res = await apiGet<{ plugins: PluginUiManifest[]; total: number }>('/plugins/active-manifests');
return res;
},
staleTime: 5 * 60 * 1000, // 5 min
refetchOnMount: true,
});
}
+33 -1
View File
@@ -1,5 +1,5 @@
/**
* Plugin management hooks: list, install, activate, deactivate, uninstall.
* Plugin management hooks: list, install, activate, deactivate, uninstall, upload, install-url.
*/
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
@@ -65,3 +65,35 @@ export function useUninstallPlugin() {
},
});
}
export function useUploadPlugin() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (file: File) => {
const formData = new FormData();
formData.append('file', file);
const { default: apiClient } = await import('./client');
const res = await apiClient.post('/api/v1/plugins/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return res.data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['plugins'] });
},
});
}
export function useInstallPluginFromUrl() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (url: string) => {
const { default: apiClient } = await import('./client');
const res = await apiClient.post('/api/v1/plugins/install-url', { url });
return res.data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['plugins'] });
},
});
}
@@ -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();
});
});
+18 -1
View File
@@ -1,11 +1,14 @@
import React from 'react';
import { NavLink, Outlet } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePluginStore } from '@/store/pluginStore';
import * as LucideIcons from 'lucide-react';
export function SettingsPage() {
const { t } = useTranslation();
const pluginSettingsPages = usePluginStore(s => s.getAllSettingsPages());
const navItems = [
const hardcodedNavItems = [
{ to: '/settings/system', label: t('systemSettings.title'), icon: '\u2699\ufe0f' },
{ to: '/settings/roles', label: t('settings.roles'), icon: '\ud83d\udd11' },
{ to: '/settings/users', label: t('settings.users'), icon: '\ud83d\udc65' },
@@ -21,6 +24,20 @@ export function SettingsPage() {
{ to: '/settings/theme', label: t('settings.theme', 'Theme'), icon: '\ud83c\udfa8' },
];
const existingPaths = new Set(hardcodedNavItems.map(item => item.to));
const pluginNavItems = pluginSettingsPages
.filter(p => !existingPaths.has(`/settings/${p.path}`))
.map(p => ({
to: `/settings/${p.path}`,
label: t(p.label_key, p.label),
icon: (() => {
const Icon = (LucideIcons as any)[p.icon];
return Icon ? React.createElement(Icon, { className: 'w-4 h-4' }) : '\ud83d\udce6';
})(),
}));
const navItems = [...hardcodedNavItems, ...pluginNavItems];
return (
<div className="flex max-w-7xl mx-auto" data-testid="settings-page">
<aside className="w-64 flex-shrink-0 border-r border-secondary-200 p-4 min-h-[calc(100vh-4rem)]">
+130 -3
View File
@@ -1,6 +1,14 @@
import React, { useState } from 'react';
import React, { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { usePlugins, useInstallPlugin, useActivatePlugin, useDeactivatePlugin, useUninstallPlugin } from '@/api/hooks';
import {
usePlugins,
useInstallPlugin,
useActivatePlugin,
useDeactivatePlugin,
useUninstallPlugin,
useUploadPlugin,
useInstallPluginFromUrl,
} from '@/api/hooks';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
@@ -44,6 +52,122 @@ function statusLabel(status: string, t: (k: string) => string): string {
}
}
function InstallPluginSection() {
const { t } = useTranslation();
const toast = useToast();
const uploadMutation = useUploadPlugin();
const installUrlMutation = useInstallPluginFromUrl();
const fileInputRef = useRef<HTMLInputElement>(null);
const [url, setUrl] = useState('');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0] || null;
setSelectedFile(file);
};
const handleUpload = async () => {
if (!selectedFile) {
toast.error(t('settings.pluginSelectFile'));
return;
}
try {
await uploadMutation.mutateAsync(selectedFile);
toast.success(t('settings.pluginUploadedSuccess'));
setSelectedFile(null);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
} catch (err: any) {
toast.error(err.message || t('common.error'));
}
};
const handleInstallUrl = async () => {
if (!url.trim()) {
toast.error(t('settings.pluginEnterUrl'));
return;
}
try {
await installUrlMutation.mutateAsync(url.trim());
toast.success(t('settings.pluginUrlInstalledSuccess'));
setUrl('');
} catch (err: any) {
toast.error(err.message || t('common.error'));
}
};
const isBusy = uploadMutation.isPending || installUrlMutation.isPending;
return (
<Card className="mb-6">
<div className="p-4">
<h2 className="text-lg font-semibold text-secondary-900 mb-4">
{t('settings.installPlugin')}
</h2>
{/* ZIP Upload */}
<div className="mb-4">
<label className="block text-sm font-medium text-secondary-700 mb-2">
{t('settings.uploadZip')}
</label>
<div className="flex items-center gap-3">
<input
ref={fileInputRef}
type="file"
accept=".zip"
onChange={handleFileSelect}
className="block w-full text-sm text-secondary-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-primary-50 file:text-primary-700 hover:file:bg-primary-100"
data-testid="plugin-zip-upload-input"
/>
<Button
size="sm"
onClick={handleUpload}
isLoading={uploadMutation.isPending}
disabled={!selectedFile || isBusy}
data-testid="plugin-upload-btn"
>
{t('settings.upload')}
</Button>
</div>
{selectedFile && (
<p className="text-xs text-secondary-400 mt-1">
{selectedFile.name} ({(selectedFile.size / 1024).toFixed(1)} KB)
</p>
)}
</div>
{/* URL Install */}
<div>
<label className="block text-sm font-medium text-secondary-700 mb-2">
{t('settings.installFromUrl')}
</label>
<div className="flex items-center gap-3">
<input
type="text"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://example.com/plugin.zip"
className="flex-1 rounded-lg border border-secondary-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent"
data-testid="plugin-url-input"
/>
<Button
size="sm"
onClick={handleInstallUrl}
isLoading={installUrlMutation.isPending}
disabled={!url.trim() || isBusy}
data-testid="plugin-install-url-btn"
>
{t('settings.install')}
</Button>
</div>
</div>
</div>
</Card>
);
}
export function SettingsPluginsPage() {
const { t } = useTranslation();
const toast = useToast();
@@ -133,6 +257,9 @@ export function SettingsPluginsPage() {
</Button>
</div>
{/* Install Plugin Section */}
<InstallPluginSection />
{plugins.length === 0 ? (
<EmptyState title={t('settings.noPlugins')} />
) : (
@@ -252,4 +379,4 @@ export function SettingsPluginsPage() {
</ConfirmDialog>
</div>
);
}
}
+3
View File
@@ -6,6 +6,7 @@ import { LoginPage } from '@/pages/Login';
import { PasswordResetRequestPage } from '@/pages/PasswordResetRequest';
import { PasswordResetConfirmPage } from '@/pages/PasswordResetConfirm';
import { Loader2 } from 'lucide-react';
import { PluginRouteRenderer } from '@/components/plugins/PluginRouteRenderer';
// Lazy-loaded pages (code-splitting)
const DashboardPage = React.lazy(() => import('@/pages/Dashboard').then(m => ({ default: m.DashboardPage })));
@@ -100,8 +101,10 @@ const router = createBrowserRouter([
{ path: 'ai', element: withSuspense(<AISettingsPage />) },
{ path: 'ai-proactive', element: withSuspense(<ProactiveAISettings />) },
{ path: 'theme', element: withSuspense(<SettingsThemePage />) },
{ path: '*', element: <PluginRouteRenderer /> },
],
},
{ path: '*', element: <PluginRouteRenderer /> },
],
},
]);
@@ -0,0 +1,187 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { usePluginStore } from '../pluginStore';
import type { PluginUiManifest } from '../pluginStore';
const mockManifests: PluginUiManifest[] = [
{
name: 'plugin_a',
display_name: 'Plugin A',
version: '1.0.0',
is_core: false,
menu_items: [
{ label_key: 'nav.a', label: 'A', path: '/a', icon: 'A', group: '', order: 200, badge_key: '' },
{ label_key: 'nav.a2', label: 'A2', path: '/a2', icon: 'A', group: '', order: 50, badge_key: '' },
],
page_routes: [
{ path: '/a', component: '@/pages/A', parent: '', protected: true, order: 200 },
],
detail_tabs: [
{ entity_type: 'contact', label_key: 'tabs.a', label: 'Tab A', component: '@/components/TabA', icon: 'A', order: 100, permission: '' },
{ entity_type: 'company', label_key: 'tabs.a2', label: 'Tab A2', component: '@/components/TabA2', icon: 'A', order: 50, permission: '' },
],
settings_pages: [
{ path: 'a', label_key: 'settings.a', label: 'Settings A', component: '@/pages/SettingsA', icon: 'A', order: 200, permission: '' },
],
dashboard_widgets: [
{ id: 'widget_a', label_key: 'widgets.a', label: 'Widget A', component: '@/components/WidgetA', icon: 'A', order: 200, col_span: 2, row_span: 1, permission: '' },
],
},
{
name: 'plugin_b',
display_name: 'Plugin B',
version: '1.0.0',
is_core: true,
menu_items: [
{ label_key: 'nav.b', label: 'B', path: '/b', icon: 'B', group: '', order: 100, badge_key: '' },
],
page_routes: [
{ path: '/b', component: '@/pages/B', parent: '', protected: true, order: 100 },
],
detail_tabs: [
{ entity_type: 'contact', label_key: 'tabs.b', label: 'Tab B', component: '@/components/TabB', icon: 'B', order: 200, permission: '' },
],
settings_pages: [
{ path: 'b', label_key: 'settings.b', label: 'Settings B', component: '@/pages/SettingsB', icon: 'B', order: 100, permission: '' },
],
dashboard_widgets: [
{ id: 'widget_b', label_key: 'widgets.b', label: 'Widget B', component: '@/components/WidgetB', icon: 'B', order: 100, col_span: 1, row_span: 1, permission: '' },
],
},
];
describe('pluginStore', () => {
beforeEach(() => {
usePluginStore.getState().reset();
});
describe('getAllMenuItems', () => {
it('returns empty array when no manifests', () => {
const items = usePluginStore.getState().getAllMenuItems();
expect(items).toHaveLength(0);
});
it('merges menu items from all manifests', () => {
usePluginStore.setState({ manifests: mockManifests });
const items = usePluginStore.getState().getAllMenuItems();
expect(items).toHaveLength(3);
});
it('sorts menu items by order ascending', () => {
usePluginStore.setState({ manifests: mockManifests });
const items = usePluginStore.getState().getAllMenuItems();
expect(items[0].order).toBe(50);
expect(items[1].order).toBe(100);
expect(items[2].order).toBe(200);
});
});
describe('getDetailTabsForEntity', () => {
it('returns empty array when no manifests', () => {
const tabs = usePluginStore.getState().getDetailTabsForEntity('contact');
expect(tabs).toHaveLength(0);
});
it('filters tabs by entity_type', () => {
usePluginStore.setState({ manifests: mockManifests });
const contactTabs = usePluginStore.getState().getDetailTabsForEntity('contact');
expect(contactTabs).toHaveLength(2);
expect(contactTabs.every((t) => t.entity_type === 'contact')).toBe(true);
});
it('returns empty array for entity with no tabs', () => {
usePluginStore.setState({ manifests: mockManifests });
const taskTabs = usePluginStore.getState().getDetailTabsForEntity('task');
expect(taskTabs).toHaveLength(0);
});
it('sorts tabs by order ascending', () => {
usePluginStore.setState({ manifests: mockManifests });
const contactTabs = usePluginStore.getState().getDetailTabsForEntity('contact');
expect(contactTabs[0].order).toBe(100);
expect(contactTabs[1].order).toBe(200);
});
});
describe('getAllSettingsPages', () => {
it('returns empty array when no manifests', () => {
const pages = usePluginStore.getState().getAllSettingsPages();
expect(pages).toHaveLength(0);
});
it('merges settings pages from all manifests', () => {
usePluginStore.setState({ manifests: mockManifests });
const pages = usePluginStore.getState().getAllSettingsPages();
expect(pages).toHaveLength(2);
});
it('sorts settings pages by order ascending', () => {
usePluginStore.setState({ manifests: mockManifests });
const pages = usePluginStore.getState().getAllSettingsPages();
expect(pages[0].order).toBe(100);
expect(pages[1].order).toBe(200);
});
});
describe('getAllDashboardWidgets', () => {
it('returns empty array when no manifests', () => {
const widgets = usePluginStore.getState().getAllDashboardWidgets();
expect(widgets).toHaveLength(0);
});
it('merges widgets from all manifests', () => {
usePluginStore.setState({ manifests: mockManifests });
const widgets = usePluginStore.getState().getAllDashboardWidgets();
expect(widgets).toHaveLength(2);
});
it('sorts widgets by order ascending', () => {
usePluginStore.setState({ manifests: mockManifests });
const widgets = usePluginStore.getState().getAllDashboardWidgets();
expect(widgets[0].order).toBe(100);
expect(widgets[1].order).toBe(200);
});
});
describe('reset', () => {
it('clears all state', () => {
usePluginStore.setState({ manifests: mockManifests, loading: true, error: 'test', loaded: true });
usePluginStore.getState().reset();
const state = usePluginStore.getState();
expect(state.manifests).toHaveLength(0);
expect(state.loading).toBe(false);
expect(state.error).toBeNull();
expect(state.loaded).toBe(false);
});
});
describe('setManifests', () => {
it('sets manifests and marks as loaded', () => {
usePluginStore.getState().setManifests(mockManifests);
const state = usePluginStore.getState();
expect(state.manifests).toHaveLength(2);
expect(state.loaded).toBe(true);
expect(state.loading).toBe(false);
expect(state.error).toBeNull();
});
});
describe('getAllPageRoutes', () => {
it('returns empty array when no manifests', () => {
const routes = usePluginStore.getState().getAllPageRoutes();
expect(routes).toHaveLength(0);
});
it('merges page routes from all manifests', () => {
usePluginStore.setState({ manifests: mockManifests });
const routes = usePluginStore.getState().getAllPageRoutes();
expect(routes).toHaveLength(2);
});
it('sorts page routes by order ascending', () => {
usePluginStore.setState({ manifests: mockManifests });
const routes = usePluginStore.getState().getAllPageRoutes();
expect(routes[0].order).toBe(100);
expect(routes[1].order).toBe(200);
});
});
});
+128
View File
@@ -0,0 +1,128 @@
import { create } from 'zustand';
export interface PluginMenuItem {
label_key: string;
label: string;
path: string;
icon: string;
group: string;
order: number;
badge_key: string;
}
export interface PluginPageRoute {
path: string;
component: string;
parent: string;
protected: boolean;
order: number;
}
export interface PluginDetailTab {
entity_type: string;
label_key: string;
label: string;
component: string;
icon: string;
order: number;
permission: string;
}
export interface PluginSettingsPage {
path: string;
label_key: string;
label: string;
component: string;
icon: string;
order: number;
permission: string;
}
export interface PluginDashboardWidget {
id: string;
label_key: string;
label: string;
component: string;
icon: string;
order: number;
col_span: number;
row_span: number;
permission: string;
}
export interface PluginUiManifest {
name: string;
display_name: string;
version: string;
is_core: boolean;
menu_items: PluginMenuItem[];
page_routes: PluginPageRoute[];
detail_tabs: PluginDetailTab[];
settings_pages: PluginSettingsPage[];
dashboard_widgets: PluginDashboardWidget[];
}
interface PluginState {
manifests: PluginUiManifest[];
loading: boolean;
error: string | null;
loaded: boolean;
setManifests: (manifests: PluginUiManifest[]) => void;
setLoading: (loading: boolean) => void;
setError: (error: string | null) => void;
reset: () => void;
// Computed selectors
getAllMenuItems: () => PluginMenuItem[];
getAllPageRoutes: () => PluginPageRoute[];
getDetailTabsForEntity: (entityType: string) => PluginDetailTab[];
getAllSettingsPages: () => PluginSettingsPage[];
getAllDashboardWidgets: () => PluginDashboardWidget[];
}
export const usePluginStore = create<PluginState>((set, get) => ({
manifests: [],
loading: false,
error: null,
loaded: false,
setManifests: (manifests) => set({ manifests, loaded: true, loading: false, error: null }),
setLoading: (loading) => set({ loading }),
setError: (error) => set({ error, loading: false }),
reset: () => set({ manifests: [], loading: false, error: null, loaded: false }),
getAllMenuItems: () => {
const { manifests } = get();
return manifests
.flatMap((m) => m.menu_items)
.sort((a, b) => a.order - b.order);
},
getAllPageRoutes: () => {
const { manifests } = get();
return manifests
.flatMap((m) => m.page_routes)
.sort((a, b) => a.order - b.order);
},
getDetailTabsForEntity: (entityType: string) => {
const { manifests } = get();
return manifests
.flatMap((m) => m.detail_tabs)
.filter((t) => t.entity_type === entityType)
.sort((a, b) => a.order - b.order);
},
getAllSettingsPages: () => {
const { manifests } = get();
return manifests
.flatMap((m) => m.settings_pages)
.sort((a, b) => a.order - b.order);
},
getAllDashboardWidgets: () => {
const { manifests } = get();
return manifests
.flatMap((m) => m.dashboard_widgets)
.sort((a, b) => a.order - b.order);
},
}));