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 { 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 } from 'lucide-react' import { useEffect, useMemo } from 'react' import { toast } from 'sonner' import { AgentInfo, AgentType } from '@shumai/dtos' 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, 'Name is required'), type: z.enum(['chat', 'autofill', 'embedding']), avatar: z.string().optional(), providerId: z.string().optional(), modelId: z.string().optional(), soul: z.string().optional(), thinkingLevel: z.string().optional(), systemPrompt: z.string().optional(), skills: z.array(z.string()).optional(), }) type AgentFormValues = z.infer export function AgentFormDialog({ isOpen, onClose, teamId, type, initialValues, title, }: AgentFormDialogProps) { const queryClient = useQueryClient() // 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 || [] 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: 'Provider is required', path: ['providerId'], }) } if (!data.modelId) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Model is required', path: ['modelId'], }) } } }) }, []) const form = useForm({ defaultValues: { name: initialValues?.name || '', type: type || initialValues?.type || 'chat', avatar: initialValues?.avatar || AVAILABLE_AVATARS[0], providerId: initialValues?.providerId || '', modelId: initialValues?.modelId || '', soul: initialValues?.soul || '', thinkingLevel: initialValues?.thinkingLevel || 'medium', systemPrompt: initialValues?.systemPrompt || '', skills: initialValues?.skills?.map((s) => s.skillId) || ([] 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('Agent created successfully') }, onError: (error) => { toast.error(`Error: ${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('Agent updated successfully') }, onError: (error) => { toast.error(`Error: ${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 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} Configure your AI agent's personality and capabilities.
{ 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 ( Agent Name field.handleChange(e.target.value)} placeholder="e.g., Support Assistant" aria-invalid={isInvalid} /> {isInvalid && } ) }} /> ( Agent Type )} /> ( 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 ( Provider {isInvalid && ( )} ) }} /> { const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched return ( Model {isModelsLoading && } {isInvalid && ( )} ) }} />
( Thinking Level )} />
( Agent Soul (Personality)