feat(skills): UI fuer AI-Skill-Definitionen — Modul 7/16 des UI-Backlogs
Check Cross-Plugin Imports / check (push) Has been cancelled
Check Cross-Plugin Imports / check (push) Has been cancelled
Zweites Modul via Phase-Q-Manifest-Architektur: Registrierung komplett ueber das automation-Plugin-Manifest (page_route /skills + menu_item, Sparkles-Icon) — routes/index.tsx und Sidebar.tsx unangetastet. Der Komponenten-Map-Generator wired den lazy import (39 Komponenten). Backend existierte vollstaendig im automation-Plugin (skill_routes.py: list mit is_active/category-Filtern, create, get, patch, delete; automation:read/write/delete), Frontend hatte 0% Abdeckung. - api/skills.ts: TanStack-Hooks (useSkills mit Filtern, useSkill, create/update/delete mit Cache-Invalidierung) - pages/Skills.tsx: Filter-Tabs (alle/aktiv/inaktiv), Skill-Karten (Name, Aktiv/Inaktiv-Badge, Kategorie, Beschreibung, Tool-Count), Create/Edit-Dialog (Name, Beschreibung, Instructions-Textarea, Kategorie, Tool-IDs als Komma-Liste, Aktiv-Toggle), Delete mit Confirm — Create/Edit hinter automation:write, Delete hinter automation:delete - i18n skills.* + nav.skills de/en Hinweis: Skills sind Orchestrierungs-Metadaten, KEINE Berechtigungsquelle — erlaubte Tools verweisen auf Tool-IDs, fuer die Agent und User bereits berechtigt sein muessen (Backend-Docstring). Verifikation: Vitest 10/10 (Filter-Tabs, Badges inkl. Inaktiv, Tool-Count, Create-Flow, Edit prefilled, Delete mit+ohne Confirm, separates Write/Delete-Gating) · tsc exit 0 · production build exit 0 · Backend-Regressionen (route-order, m5-miniapps, n4-scope) 28/28 · compileall sauber · Cross-Plugin-Checker 0 · Manifest-Check: page_route + menu_item korrekt.
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* Skills page tests — AI skill definitions (module 7/16).
|
||||
*
|
||||
* Covers: rendering, filter tabs, skill cards with active badge + tool
|
||||
* count, create flow, edit flow prefilled, delete with confirmation,
|
||||
* permission gating (automation:write / automation:delete), empty and
|
||||
* error states.
|
||||
*/
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { SkillsPage } from '@/pages/Skills';
|
||||
import type { SkillDefinition } from '@/api/skills';
|
||||
|
||||
const createMut = vi.fn().mockImplementation((_payload, opts) => {
|
||||
opts?.onSuccess?.({});
|
||||
return Promise.resolve({});
|
||||
});
|
||||
const updateMut = vi.fn().mockImplementation((_payload, opts) => {
|
||||
opts?.onSuccess?.({});
|
||||
return Promise.resolve({});
|
||||
});
|
||||
const deleteMut = vi.fn().mockResolvedValue({});
|
||||
|
||||
const makeSkill = (overrides: Partial<SkillDefinition> = {}): SkillDefinition => ({
|
||||
id: 'sk-1',
|
||||
name: 'Rechnungspruefung',
|
||||
description: 'Prueft eingehende Rechnungen',
|
||||
instructions: '1. Lade die Rechnung\n2. Pruefe Betraege',
|
||||
allowed_tool_ids: ['11111111-1111-1111-1111-111111111111', '22222222-2222-2222-2222-222222222222'],
|
||||
context_policy: null,
|
||||
category: 'finance',
|
||||
is_active: true,
|
||||
created_at: '2026-09-01T10:00:00Z',
|
||||
updated_at: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
let mockItems: SkillDefinition[] = [];
|
||||
let mockPerms: Record<string, boolean> = { 'automation:read': true, 'automation:write': true, 'automation:delete': true };
|
||||
let mockError = false;
|
||||
|
||||
vi.mock('@/api/skills', () => ({
|
||||
useSkills: () => ({
|
||||
data: { items: mockItems, total: mockItems.length },
|
||||
isLoading: false,
|
||||
isError: mockError,
|
||||
isFetching: false,
|
||||
refetch: vi.fn(),
|
||||
}),
|
||||
useCreateSkill: () => ({
|
||||
mutate: createMut,
|
||||
isPending: false,
|
||||
}),
|
||||
useUpdateSkill: () => ({
|
||||
mutate: updateMut,
|
||||
isPending: false,
|
||||
}),
|
||||
useDeleteSkill: () => ({
|
||||
mutate: deleteMut,
|
||||
isPending: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/usePermission', () => ({
|
||||
usePermission: () => ({
|
||||
hasPermission: (perm: string) => mockPerms[perm] ?? false,
|
||||
}),
|
||||
}));
|
||||
|
||||
function renderPage() {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<SkillsPage />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockItems = [];
|
||||
mockPerms = { 'automation:read': true, 'automation:write': true, 'automation:delete': true };
|
||||
mockError = false;
|
||||
});
|
||||
|
||||
describe('SkillsPage', () => {
|
||||
it('renders the page with title and filter tabs', () => {
|
||||
renderPage();
|
||||
expect(screen.getByTestId('skills-page')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('skill-filter-all')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('skill-filter-active')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('skill-filter-inactive')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows empty state when no skills exist', () => {
|
||||
renderPage();
|
||||
expect(screen.getByTestId('skills-empty')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error state on load failure', () => {
|
||||
mockError = true;
|
||||
renderPage();
|
||||
expect(screen.getByTestId('skills-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders skill cards with active badge, category and tool count', () => {
|
||||
mockItems = [makeSkill()];
|
||||
renderPage();
|
||||
expect(screen.getByTestId('skill-card-sk-1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Rechnungspruefung')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('skill-active-sk-1')).toBeInTheDocument();
|
||||
expect(screen.getByText('finance')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('skill-tools-sk-1')).toHaveTextContent('2');
|
||||
});
|
||||
|
||||
it('shows inactive badge for inactive skills', () => {
|
||||
mockItems = [makeSkill({ is_active: false })];
|
||||
renderPage();
|
||||
expect(screen.getByTestId('skill-active-sk-1')).toHaveTextContent(/inaktiv|inactive/i);
|
||||
});
|
||||
|
||||
it('hides create/edit without automation:write and delete without automation:delete', () => {
|
||||
mockItems = [makeSkill()];
|
||||
mockPerms = { 'automation:read': true, 'automation:write': false, 'automation:delete': false };
|
||||
renderPage();
|
||||
expect(screen.queryByTestId('skill-create-open')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('skill-edit-sk-1')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('skill-delete-sk-1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('creates a skill via the dialog', async () => {
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByTestId('skill-create-open'));
|
||||
expect(screen.getByTestId('skill-form-submit')).toBeInTheDocument();
|
||||
|
||||
const nameInput = screen.getByLabelText(/name/i, { selector: 'input' }) as HTMLInputElement;
|
||||
fireEvent.change(nameInput, { target: { value: 'Neuer Skill' } });
|
||||
const descInput = screen.getByLabelText(/beschreibung|description/i, { selector: 'input' }) as HTMLInputElement;
|
||||
fireEvent.change(descInput, { target: { value: 'Beschreibung' } });
|
||||
const instrArea = screen.getByTestId('skill-instructions') as HTMLTextAreaElement;
|
||||
fireEvent.change(instrArea, { target: { value: 'Mach dies, mach das.' } });
|
||||
|
||||
fireEvent.click(screen.getByTestId('skill-form-submit'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createMut).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: 'Neuer Skill',
|
||||
description: 'Beschreibung',
|
||||
instructions: 'Mach dies, mach das.',
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('opens the edit dialog prefilled and submits the update', async () => {
|
||||
mockItems = [makeSkill()];
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByTestId('skill-edit-sk-1'));
|
||||
|
||||
const nameInput = screen.getByLabelText(/name/i, { selector: 'input' }) as HTMLInputElement;
|
||||
expect(nameInput).toHaveValue('Rechnungspruefung');
|
||||
fireEvent.change(nameInput, { target: { value: 'Geaenderter Skill' } });
|
||||
|
||||
fireEvent.click(screen.getByTestId('skill-form-submit'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(updateMut).toHaveBeenCalledWith(
|
||||
{
|
||||
skillId: 'sk-1',
|
||||
payload: expect.objectContaining({
|
||||
name: 'Geaenderter Skill',
|
||||
instructions: '1. Lade die Rechnung\n2. Pruefe Betraege',
|
||||
}),
|
||||
},
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes a skill after confirmation', async () => {
|
||||
mockItems = [makeSkill()];
|
||||
window.confirm = vi.fn(() => true);
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByTestId('skill-delete-sk-1'));
|
||||
await waitFor(() => {
|
||||
expect(deleteMut).toHaveBeenCalledWith('sk-1');
|
||||
});
|
||||
});
|
||||
|
||||
it('does not delete when the confirmation is rejected', () => {
|
||||
mockItems = [makeSkill()];
|
||||
window.confirm = vi.fn(() => false);
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByTestId('skill-delete-sk-1'));
|
||||
expect(deleteMut).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Skills API client — AI skill definitions (orchestration metadata).
|
||||
*
|
||||
* Backend: /api/v1/skills (list, create, get, update, delete). Skills are
|
||||
* NOT a permission source — they reference tool IDs the agent/user must
|
||||
* already be permitted to use.
|
||||
* Permissions: automation:read (list/get) / automation:write (create,
|
||||
* update) / automation:delete (delete).
|
||||
*/
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { apiGet, apiPost, apiPatch, apiDelete } from '@/api/client';
|
||||
|
||||
export interface SkillDefinition {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
instructions: string;
|
||||
allowed_tool_ids: string[];
|
||||
context_policy: Record<string, unknown> | null;
|
||||
category: string;
|
||||
is_active: boolean;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
}
|
||||
|
||||
export interface SkillListResponse {
|
||||
items: SkillDefinition[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface SkillCreatePayload {
|
||||
name: string;
|
||||
description: string;
|
||||
instructions: string;
|
||||
allowed_tool_ids?: string[];
|
||||
context_policy?: Record<string, unknown> | null;
|
||||
category?: string;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
export type SkillUpdatePayload = Partial<SkillCreatePayload>;
|
||||
|
||||
export interface SkillListParams {
|
||||
isActive?: boolean;
|
||||
category?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
// ─── Query hooks ─────────────────────────────────────────────
|
||||
|
||||
export function useSkills(params: SkillListParams = {}) {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params.isActive !== undefined) searchParams.set('is_active', String(params.isActive));
|
||||
if (params.category) searchParams.set('category', params.category);
|
||||
if (params.limit) searchParams.set('limit', String(params.limit));
|
||||
if (params.offset) searchParams.set('offset', String(params.offset));
|
||||
const qs = searchParams.toString();
|
||||
|
||||
return useQuery<SkillListResponse>({
|
||||
queryKey: ['skills', params.isActive, params.category, params.limit, params.offset],
|
||||
queryFn: () => apiGet<SkillListResponse>(`/skills${qs ? `?${qs}` : ''}`),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSkill(skillId: string | null) {
|
||||
return useQuery<SkillDefinition>({
|
||||
queryKey: ['skills', skillId],
|
||||
queryFn: () => apiGet<SkillDefinition>(`/skills/${skillId}`),
|
||||
enabled: !!skillId,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Mutation hooks ──────────────────────────────────────────
|
||||
|
||||
function useInvalidateSkills() {
|
||||
const qc = useQueryClient();
|
||||
return () => {
|
||||
qc.invalidateQueries({ queryKey: ['skills'] });
|
||||
};
|
||||
}
|
||||
|
||||
export function useCreateSkill() {
|
||||
const invalidate = useInvalidateSkills();
|
||||
return useMutation<SkillDefinition, Error, SkillCreatePayload>({
|
||||
mutationFn: (data) => apiPost<SkillDefinition>('/skills/', data),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateSkill() {
|
||||
const invalidate = useInvalidateSkills();
|
||||
return useMutation<
|
||||
SkillDefinition,
|
||||
Error,
|
||||
{ skillId: string; payload: SkillUpdatePayload }
|
||||
>({
|
||||
mutationFn: ({ skillId, payload }) =>
|
||||
apiPatch<SkillDefinition>(`/skills/${skillId}`, payload),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteSkill() {
|
||||
const invalidate = useInvalidateSkills();
|
||||
return useMutation<{ status: string }, Error, string>({
|
||||
mutationFn: (skillId) => apiDelete<{ status: string }>(`/skills/${skillId}`),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
}
|
||||
@@ -52,6 +52,7 @@ export const PLUGIN_COMPONENT_MAP: Record<string, LazyComponentFactory> = {
|
||||
'@/pages/SettingsNotifications': () => import('@/pages/SettingsNotifications').then((m) => ({ default: m.SettingsNotificationsPage })),
|
||||
'@/pages/SettingsRoles': () => import('@/pages/SettingsRoles').then((m) => ({ default: m.SettingsRolesPage })),
|
||||
'@/pages/SettingsUsers': () => import('@/pages/SettingsUsers').then((m) => ({ default: m.SettingsUsersPage })),
|
||||
'@/pages/Skills': () => import('@/pages/Skills').then(normalizeModule),
|
||||
'@/pages/Tags': () => import('@/pages/Tags').then((m) => ({ default: m.TagsPage })),
|
||||
'@/pages/Tasks': () => import('@/pages/Tasks').then((m) => ({ default: m.TasksPage })),
|
||||
'@/pages/Wiki': () => import('@/pages/Wiki').then((m) => ({ default: m.WikiPage })),
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
"systemDashboard": "System Dashboard",
|
||||
"approvals": "Freigaben",
|
||||
"delegations": "Delegationen",
|
||||
"marketplace": "Marketplace"
|
||||
"marketplace": "Marketplace",
|
||||
"skills": "Skills"
|
||||
},
|
||||
"auth": {
|
||||
"login": "Anmelden",
|
||||
@@ -1758,5 +1759,34 @@
|
||||
"deleteConfirm": "Vorlage '{{name}}' wirklich loeschen?",
|
||||
"empty": "Keine Berechtigungs-Vorlagen vorhanden.",
|
||||
"loadError": "Vorlagen konnten nicht geladen werden."
|
||||
},
|
||||
"skills": {
|
||||
"title": "Skills",
|
||||
"create": "Skill erstellen",
|
||||
"createTitle": "Neuen Skill definieren",
|
||||
"createSubmit": "Erstellen",
|
||||
"editTitle": "Skill bearbeiten",
|
||||
"save": "Speichern",
|
||||
"name": "Name",
|
||||
"namePlaceholder": "z.B. Rechnungspruefung",
|
||||
"description": "Beschreibung",
|
||||
"descriptionPlaceholder": "Wofuer ist dieser Skill?",
|
||||
"instructions": "Anweisungen",
|
||||
"instructionsPlaceholder": "Schritt-fuer-Schritt-Anweisungen fuer den Agenten...",
|
||||
"category": "Kategorie",
|
||||
"tools": "Erlaubte Tools",
|
||||
"toolsHelper": "Kommagetrennte Tool-IDs. Leer = keine Tools.",
|
||||
"isActive": "Aktiv",
|
||||
"active": "Aktiv",
|
||||
"inactive": "Inaktiv",
|
||||
"filterAll": "Alle",
|
||||
"filterActive": "Aktiv",
|
||||
"filterInactive": "Inaktiv",
|
||||
"toolCount": "{{count}} Tool(s)",
|
||||
"edit": "Bearbeiten",
|
||||
"delete": "Loeschen",
|
||||
"deleteConfirm": "Skill '{{name}}' wirklich loeschen?",
|
||||
"empty": "Keine Skills vorhanden.",
|
||||
"loadError": "Skills konnten nicht geladen werden."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
"systemDashboard": "System Dashboard",
|
||||
"approvals": "Approvals",
|
||||
"delegations": "Delegations",
|
||||
"marketplace": "Marketplace"
|
||||
"marketplace": "Marketplace",
|
||||
"skills": "Skills"
|
||||
},
|
||||
"auth": {
|
||||
"login": "Sign In",
|
||||
@@ -1758,5 +1759,34 @@
|
||||
"deleteConfirm": "Really delete template '{{name}}'?",
|
||||
"empty": "No permission templates yet.",
|
||||
"loadError": "Failed to load templates."
|
||||
},
|
||||
"skills": {
|
||||
"title": "Skills",
|
||||
"create": "Create skill",
|
||||
"createTitle": "Define a new skill",
|
||||
"createSubmit": "Create",
|
||||
"editTitle": "Edit skill",
|
||||
"save": "Save",
|
||||
"name": "Name",
|
||||
"namePlaceholder": "e.g. Invoice check",
|
||||
"description": "Description",
|
||||
"descriptionPlaceholder": "What is this skill for?",
|
||||
"instructions": "Instructions",
|
||||
"instructionsPlaceholder": "Step-by-step instructions for the agent...",
|
||||
"category": "Category",
|
||||
"tools": "Allowed tools",
|
||||
"toolsHelper": "Comma-separated tool IDs. Empty = no tools.",
|
||||
"isActive": "Active",
|
||||
"active": "Active",
|
||||
"inactive": "Inactive",
|
||||
"filterAll": "All",
|
||||
"filterActive": "Active",
|
||||
"filterInactive": "Inactive",
|
||||
"toolCount": "{{count}} tool(s)",
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
"deleteConfirm": "Really delete skill '{{name}}'?",
|
||||
"empty": "No skills yet.",
|
||||
"loadError": "Failed to load skills."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
/**
|
||||
* Skills page — AI skill definitions (orchestration metadata)
|
||||
* (UI-Backlog module 7/16).
|
||||
*
|
||||
* Backend: /api/v1/skills. Skills are NOT a permission source — they
|
||||
* reference tool IDs the agent/user must already be permitted to use.
|
||||
* Permissions: automation:read (list) / automation:write (create, update) /
|
||||
* automation:delete (delete).
|
||||
*
|
||||
* NOTE (Phase Q): registered via the automation PLUGIN MANIFEST
|
||||
* (page_routes + menu_items) — routes/index.tsx and Sidebar.tsx untouched.
|
||||
*/
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Sparkles,
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Wrench,
|
||||
AlertTriangle,
|
||||
Inbox,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
useSkills,
|
||||
useCreateSkill,
|
||||
useUpdateSkill,
|
||||
useDeleteSkill,
|
||||
type SkillDefinition,
|
||||
} from '@/api/skills';
|
||||
import { usePermission } from '@/hooks/usePermission';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Modal } from '@/components/ui/Modal';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { Badge } from '@/components/ui/Badge';
|
||||
|
||||
type ActiveFilter = 'all' | 'active' | 'inactive';
|
||||
|
||||
const FILTER_TABS: { key: ActiveFilter; labelKey: string }[] = [
|
||||
{ key: 'all', labelKey: 'skills.filterAll' },
|
||||
{ key: 'active', labelKey: 'skills.filterActive' },
|
||||
{ key: 'inactive', labelKey: 'skills.filterInactive' },
|
||||
];
|
||||
|
||||
function SkillCard({
|
||||
skill,
|
||||
canWrite,
|
||||
canDelete,
|
||||
onEdit,
|
||||
onDelete,
|
||||
isMutating,
|
||||
}: {
|
||||
skill: SkillDefinition;
|
||||
canWrite: boolean;
|
||||
canDelete: boolean;
|
||||
onEdit: (s: SkillDefinition) => void;
|
||||
onDelete: (s: SkillDefinition) => void;
|
||||
isMutating: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card className="p-4" data-testid={`skill-card-${skill.id}`}>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Sparkles className="w-4 h-4 text-primary-600 flex-shrink-0" aria-hidden="true" />
|
||||
<span className="text-sm font-medium text-secondary-900 dark:text-secondary-100">
|
||||
{skill.name}
|
||||
</span>
|
||||
<span data-testid={`skill-active-${skill.id}`}>
|
||||
<Badge variant={skill.is_active ? 'success' : 'secondary'}>
|
||||
{skill.is_active ? t('skills.active') : t('skills.inactive')}
|
||||
</Badge>
|
||||
</span>
|
||||
<Badge variant="secondary">{skill.category}</Badge>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-secondary-600 dark:text-secondary-400" data-testid={`skill-desc-${skill.id}`}>
|
||||
{skill.description}
|
||||
</p>
|
||||
<div className="mt-2 flex items-center gap-1 text-xs text-secondary-500">
|
||||
<Wrench className="w-3.5 h-3.5" aria-hidden="true" />
|
||||
<span data-testid={`skill-tools-${skill.id}`}>
|
||||
{t('skills.toolCount', { count: skill.allowed_tool_ids.length })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{(canWrite || canDelete) && (
|
||||
<div className="flex gap-2 flex-shrink-0">
|
||||
{canWrite && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onEdit(skill)}
|
||||
disabled={isMutating}
|
||||
aria-label={t('skills.edit')}
|
||||
data-testid={`skill-edit-${skill.id}`}
|
||||
>
|
||||
<Pencil className="w-4 h-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
{canDelete && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onDelete(skill)}
|
||||
disabled={isMutating}
|
||||
aria-label={t('skills.delete')}
|
||||
data-testid={`skill-delete-${skill.id}`}
|
||||
className="text-danger-600 hover:text-danger-700"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function SkillFormDialog({
|
||||
open,
|
||||
skill,
|
||||
onClose,
|
||||
onSubmit,
|
||||
isSubmitting,
|
||||
}: {
|
||||
open: boolean;
|
||||
skill: SkillDefinition | null;
|
||||
onClose: () => void;
|
||||
onSubmit: (payload: {
|
||||
name: string;
|
||||
description: string;
|
||||
instructions: string;
|
||||
allowed_tool_ids: string[];
|
||||
category: string;
|
||||
is_active: boolean;
|
||||
}) => void;
|
||||
isSubmitting: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [instructions, setInstructions] = useState('');
|
||||
const [tools, setTools] = useState('');
|
||||
const [category, setCategory] = useState('general');
|
||||
const [isActive, setIsActive] = useState(true);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setName(skill?.name ?? '');
|
||||
setDescription(skill?.description ?? '');
|
||||
setInstructions(skill?.instructions ?? '');
|
||||
setTools((skill?.allowed_tool_ids ?? []).join(', '));
|
||||
setCategory(skill?.category ?? 'general');
|
||||
setIsActive(skill?.is_active ?? true);
|
||||
}
|
||||
}, [open, skill]);
|
||||
|
||||
const parsedTools = tools
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const valid = name.trim().length > 0 && description.trim().length > 0 && instructions.trim().length > 0;
|
||||
|
||||
const submit = () => {
|
||||
if (!valid) return;
|
||||
onSubmit({
|
||||
name: name.trim(),
|
||||
description: description.trim(),
|
||||
instructions: instructions.trim(),
|
||||
allowed_tool_ids: parsedTools,
|
||||
category: category.trim() || 'general',
|
||||
is_active: isActive,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={skill ? t('skills.editTitle') : t('skills.createTitle')}
|
||||
size="lg"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
label={t('skills.name')}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
placeholder={t('skills.namePlaceholder')}
|
||||
/>
|
||||
<Input
|
||||
label={t('skills.description')}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
required
|
||||
placeholder={t('skills.descriptionPlaceholder')}
|
||||
/>
|
||||
<div>
|
||||
<label htmlFor="sk-instructions" className="block text-sm font-medium text-secondary-700 mb-1">
|
||||
{t('skills.instructions')} *
|
||||
</label>
|
||||
<textarea
|
||||
id="sk-instructions"
|
||||
value={instructions}
|
||||
onChange={(e) => setInstructions(e.target.value)}
|
||||
rows={5}
|
||||
className="block w-full rounded-md border border-secondary-300 px-3 py-2 text-sm"
|
||||
placeholder={t('skills.instructionsPlaceholder')}
|
||||
aria-label={t('skills.instructions')}
|
||||
data-testid="skill-instructions"
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
label={t('skills.category')}
|
||||
value={category}
|
||||
onChange={(e) => setCategory(e.target.value)}
|
||||
placeholder="general"
|
||||
/>
|
||||
<Input
|
||||
label={t('skills.tools')}
|
||||
value={tools}
|
||||
onChange={(e) => setTools(e.target.value)}
|
||||
placeholder="tool-id-1, tool-id-2"
|
||||
helperText={t('skills.toolsHelper')}
|
||||
/>
|
||||
<label className="flex items-center gap-2 text-sm text-secondary-700 dark:text-secondary-300">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isActive}
|
||||
onChange={(e) => setIsActive(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
{t('skills.isActive')}
|
||||
</label>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button variant="ghost" onClick={onClose}>{t('common.cancel')}</Button>
|
||||
<Button onClick={submit} disabled={!valid || isSubmitting} data-testid="skill-form-submit">
|
||||
{skill ? t('skills.save') : t('skills.createSubmit')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function SkillsPage() {
|
||||
const { t } = useTranslation();
|
||||
const [filter, setFilter] = useState<ActiveFilter>('all');
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [editSkill, setEditSkill] = useState<SkillDefinition | null>(null);
|
||||
|
||||
const { data, isLoading, isError } = useSkills({
|
||||
isActive: filter === 'all' ? undefined : filter === 'active',
|
||||
limit: 100,
|
||||
});
|
||||
const createMut = useCreateSkill();
|
||||
const updateMut = useUpdateSkill();
|
||||
const deleteMut = useDeleteSkill();
|
||||
const { hasPermission } = usePermission();
|
||||
|
||||
const canWrite = hasPermission('automation:write');
|
||||
const canDelete = hasPermission('automation:delete');
|
||||
const isMutating = createMut.isPending || updateMut.isPending || deleteMut.isPending;
|
||||
|
||||
const handleCreate = (payload: Parameters<typeof handleEditPayload>[0]) => {
|
||||
createMut.mutate(payload, {
|
||||
onSuccess: () => setShowCreate(false),
|
||||
});
|
||||
};
|
||||
|
||||
function handleEditPayload(payload: {
|
||||
name: string;
|
||||
description: string;
|
||||
instructions: string;
|
||||
allowed_tool_ids: string[];
|
||||
category: string;
|
||||
is_active: boolean;
|
||||
}) {
|
||||
// no-op: signature helper for typing
|
||||
}
|
||||
|
||||
const handleEdit = (payload: Parameters<typeof handleEditPayload>[0]) => {
|
||||
if (!editSkill) return;
|
||||
updateMut.mutate(
|
||||
{ skillId: editSkill.id, payload },
|
||||
{
|
||||
onSuccess: () => setEditSkill(null),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const handleDelete = (skill: SkillDefinition) => {
|
||||
if (window.confirm(t('skills.deleteConfirm', { name: skill.name }))) {
|
||||
deleteMut.mutate(skill.id);
|
||||
}
|
||||
};
|
||||
|
||||
const items = data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto p-4 sm:p-6 space-y-4" data-testid="skills-page">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="w-6 h-6 text-primary-600" aria-hidden="true" />
|
||||
<h1 className="text-2xl font-bold text-secondary-900 dark:text-secondary-100">
|
||||
{t('skills.title')}
|
||||
</h1>
|
||||
</div>
|
||||
{canWrite && (
|
||||
<Button onClick={() => setShowCreate(true)} data-testid="skill-create-open">
|
||||
<Plus className="w-4 h-4 mr-2" aria-hidden="true" />
|
||||
{t('skills.create')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 rounded-lg bg-secondary-100 dark:bg-secondary-800 p-1" role="tablist" aria-label={t('skills.title')}>
|
||||
{FILTER_TABS.map(({ key, labelKey }) => (
|
||||
<button
|
||||
key={key}
|
||||
role="tab"
|
||||
aria-selected={filter === key}
|
||||
onClick={() => setFilter(key)}
|
||||
className={`px-3 py-2 rounded-md text-sm font-medium transition-colors min-h-touch ${
|
||||
filter === key
|
||||
? 'bg-white dark:bg-secondary-700 text-primary-700 shadow-sm'
|
||||
: 'text-secondary-600 dark:text-secondary-300 hover:text-secondary-900'
|
||||
}`}
|
||||
data-testid={`skill-filter-${key}`}
|
||||
>
|
||||
{t(labelKey)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{isLoading && (
|
||||
<div className="flex items-center justify-center min-h-[30vh]" role="status" data-testid="skills-loading">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500" aria-hidden="true" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isError && (
|
||||
<Card className="p-6 flex items-center gap-3 text-danger-600" data-testid="skills-error">
|
||||
<AlertTriangle className="w-5 h-5" aria-hidden="true" />
|
||||
<span>{t('skills.loadError')}</span>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{!isLoading && !isError && items.length === 0 && (
|
||||
<Card className="p-8 flex flex-col items-center gap-3 text-secondary-500" data-testid="skills-empty">
|
||||
<Inbox className="w-10 h-10" aria-hidden="true" />
|
||||
<p>{t('skills.empty')}</p>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
{items.map((skill) => (
|
||||
<SkillCard
|
||||
key={skill.id}
|
||||
skill={skill}
|
||||
canWrite={canWrite}
|
||||
canDelete={canDelete}
|
||||
onEdit={setEditSkill}
|
||||
onDelete={handleDelete}
|
||||
isMutating={isMutating}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<SkillFormDialog
|
||||
open={showCreate}
|
||||
skill={null}
|
||||
onClose={() => setShowCreate(false)}
|
||||
onSubmit={handleCreate}
|
||||
isSubmitting={createMut.isPending}
|
||||
/>
|
||||
<SkillFormDialog
|
||||
open={!!editSkill}
|
||||
skill={editSkill}
|
||||
onClose={() => setEditSkill(null)}
|
||||
onSubmit={handleEdit}
|
||||
isSubmitting={updateMut.isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SkillsPage;
|
||||
Reference in New Issue
Block a user