import { client } from '@/ui/api/client' import { Button } from '@/ui/components/ui/button' import { Input } from '@/ui/components/ui/input' import { Label } from '@/ui/components/ui/label' import { Badge } from '@/ui/components/ui/badge' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/ui/components/ui/dialog' import { Field, FieldLabel, FieldError } from '@/ui/components/ui/field' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/ui/components/ui/select' import { Switch } from '@/ui/components/ui/switch' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useForm, useStore } from '@tanstack/react-form' import { Loader2, Puzzle, Server, Terminal } from 'lucide-react' import { useEffect, useMemo } from 'react' import { m } from '@/ui/paraglide/messages.js' import { toast } from 'sonner' import { AgentInfo, AgentType, ThinkingLevel, thinkingLevelSchema } from '@shumai/dtos' import { usePermissions } from '@/ui/hooks/use-permissions' import { Textarea } from '@/ui/components/ui/textarea' import { ScrollArea } from '@/ui/components/ui/scroll-area' import { z } from 'zod' import { cn } from '@/ui/lib/utils' import { AVAILABLE_AVATARS } from './avatars' interface AgentFormDialogProps { isOpen: boolean onClose: () => void teamId: string type?: AgentType initialValues?: AgentInfo title: string } const agentFormSchema = z.object({ name: z.string().min(1, m.name_is_required()), type: z.enum(['chat', 'autofill', 'embedding']), permission: z.enum(['owner', 'editor', 'reviewer']), avatar: z.string().optional(), providerId: z.string().optional(), modelId: z.string().optional(), soul: z.string().optional(), thinkingLevel: thinkingLevelSchema.optional(), systemPrompt: z.string().optional(), skills: z.array(z.string()).optional(), mcpServerIds: z.array(z.string()).optional(), deniedTools: z.array(z.string()).optional(), }) const BUILTIN_TOOLS = [ { id: 'bash', name: () => m.agent_tool_bash_name(), description: () => m.agent_tool_bash_desc(), }, { id: 'read_skill', name: () => m.agent_tool_read_skill_name(), description: () => m.agent_tool_read_skill_desc(), }, { id: 'analyze_image', name: () => m.agent_tool_analyze_image_name(), description: () => m.agent_tool_analyze_image_desc(), }, { id: 'screenshot', name: () => m.agent_tool_screenshot_name(), description: () => m.agent_tool_screenshot_desc(), }, { id: 'read_pdf_pages', name: () => m.agent_tool_read_pdf_pages_name(), description: () => m.agent_tool_read_pdf_pages_desc(), }, { id: 'list_assets', name: () => m.agent_tool_list_assets_name(), description: () => m.agent_tool_list_assets_desc(), }, { id: 'create_folder', name: () => m.agent_tool_create_folder_name(), description: () => m.agent_tool_create_folder_desc(), }, { id: 'create_file', name: () => m.agent_tool_create_file_name(), description: () => m.agent_tool_create_file_desc(), }, { id: 'create_version', name: () => m.agent_tool_create_version_name(), description: () => m.agent_tool_create_version_desc(), }, ] type AgentFormValues = z.infer export function AgentFormDialog({ isOpen, onClose, teamId, type, initialValues, title, }: AgentFormDialogProps) { const queryClient = useQueryClient() const { canAdmin } = usePermissions() // Fetch Providers const { data: providers } = useQuery({ queryKey: ['teams', teamId, 'providers'], queryFn: async () => { const res = await client.api.teams[':teamId'].providers.$get({ param: { teamId }, }) if (!res.ok) throw new Error('Failed to fetch providers') return await res.json() }, enabled: isOpen, }) // Fetch Skills const { data: skillsData } = useQuery({ queryKey: ['teams', teamId, 'skills'], queryFn: async () => { const res = await client.api.teams[':teamId'].skills.$get({ param: { teamId }, }) if (!res.ok) throw new Error('Failed to fetch skills') return await res.json() }, enabled: isOpen, }) const allSkills = skillsData?.skills || [] // Fetch MCP Servers const { data: mcpData } = useQuery({ queryKey: ['teams', teamId, 'mcp', 'servers'], queryFn: async () => { const res = await client.api.teams[':teamId'].mcp.servers.$get({ param: { teamId }, }) if (!res.ok) throw new Error('Failed to fetch MCP servers') return await res.json() }, enabled: isOpen, }) const allMcpServers = mcpData?.servers || [] const schema = useMemo(() => { return agentFormSchema.superRefine((data, ctx) => { if (data.type === 'chat' || data.type === 'autofill') { if (!data.providerId) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: m.provider_is_required(), path: ['providerId'], }) } if (!data.modelId) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: m.model_is_required(), path: ['modelId'], }) } } }) }, []) const form = useForm({ defaultValues: { name: initialValues?.name || '', type: initialValues?.type || type || 'chat', permission: initialValues?.permission || 'reviewer', avatar: initialValues?.avatar || AVAILABLE_AVATARS[0], providerId: initialValues?.providerId || '', modelId: initialValues?.modelId || '', soul: initialValues?.soul || '', thinkingLevel: initialValues?.thinkingLevel || 'off', systemPrompt: initialValues?.systemPrompt || '', skills: initialValues?.skills?.map((s) => s.skillId) || ([] as string[]), mcpServerIds: initialValues?.mcpServerIds || ([] as string[]), deniedTools: initialValues?.deniedTools || ([] as string[]), } as AgentFormValues, validators: { onChange: schema, }, onSubmit: async ({ value }) => { try { if (initialValues?.id) { await updateMutation.mutateAsync({ id: initialValues.id, values: value }) } else { await createMutation.mutateAsync(value) } } catch { // Error handled by mutation } }, }) // Fetch models for selected provider const selectedProviderId = useStore(form.store, (s) => s.values.providerId) const { data: models, isLoading: isModelsLoading } = useQuery({ queryKey: ['teams', teamId, 'providers', selectedProviderId, 'models'], queryFn: async () => { const res = await client.api.providers[':id'].models.$get({ param: { id: selectedProviderId! }, }) if (!res.ok) throw new Error('Failed to fetch models') return await res.json() }, enabled: !!selectedProviderId && isOpen, }) const createMutation = useMutation({ mutationFn: async (values: AgentFormValues) => { const res = await client.api.teams[':teamId'].agents.$post({ param: { teamId }, json: values, }) if (!res.ok) throw new Error('Failed to create agent') return await res.json() }, onSuccess: () => { onClose() queryClient.invalidateQueries({ queryKey: ['agents', teamId] }) toast.success(m.agent_created_successfully()) }, onError: (error) => { toast.error(m.error_message({ message: error.message })) }, }) const updateMutation = useMutation({ mutationFn: async ({ id, values }: { id: string; values: AgentFormValues }) => { const res = await client.api.agents[':agentId'].$put({ param: { agentId: id }, json: values, }) if (!res.ok) throw new Error('Failed to update agent') return await res.json() }, onSuccess: () => { onClose() queryClient.invalidateQueries({ queryKey: ['agents', teamId] }) toast.success(m.agent_updated_successfully()) }, onError: (error) => { toast.error(m.error_message({ message: error.message })) }, }) useEffect(() => { if (isOpen) { form.reset() } }, [isOpen, initialValues, type]) const agentType = useStore(form.store, (s) => s.values.type) const isAiType = agentType === 'chat' || agentType === 'autofill' const isChatType = agentType === 'chat' const mapErrors = (errors: unknown[]) => { return errors.map((e) => { if (typeof e === 'string') return { message: e } if (e && typeof e === 'object' && 'message' in e) { return { message: String(e.message) } } return { message: String(e || '') } }) } return ( {title} {m.configure_agent_description()}
{ e.preventDefault() e.stopPropagation() form.handleSubmit() }} className="flex-1 flex flex-col min-h-0 overflow-hidden" >
{ const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched return ( {m.agent_name()} field.handleChange(e.target.value)} placeholder={m.agent_name_placeholder()} aria-invalid={isInvalid} /> {isInvalid && } ) }} /> ( {m.agent_type()} )} /> {isChatType && ( ( {m.skill_permission()} )} /> )} ( {m.agent_avatar()}
{AVAILABLE_AVATARS.map((avatarPath) => { const isSelected = field.state.value === avatarPath return ( ) })} {field.state.value && !AVAILABLE_AVATARS.includes(field.state.value) && ( )}
)} />
{isAiType && ( <>
{ const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched return ( {m.provider()} {isInvalid && ( )} ) }} /> { const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched return ( {m.model()} {isModelsLoading && } {isInvalid && ( )} ) }} />
{ const thinkingLabels: Record = { off: m.thinking_disable(), low: m.thinking_low(), medium: m.thinking_medium(), high: m.thinking_high(), } return ( {m.thinking_level()} ) }} />
( {m.agent_soul()}