import { client } from '@/ui/api/client' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/ui/components/ui/alert-dialog' import { Badge } from '@/ui/components/ui/badge' import { Button } from '@/ui/components/ui/button' import { Card, CardContent } from '@/ui/components/ui/card' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/ui/components/ui/select' import { Switch } from '@/ui/components/ui/switch' import { usePermissions } from '@/ui/hooks/use-permissions' import { cn } from '@/ui/lib/utils' import { m } from '@/ui/paraglide/messages.js' import { AgentInfo, AgentPermission, AgentType, ThinkingLevel } from '@shumai/dtos' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Bot, ChevronDown, Cpu, Loader2, MessageSquare, MoreVertical, Plus, Puzzle, Trash2, Zap, } from 'lucide-react' import { useState } from 'react' import { toast } from 'sonner' import { AgentFormDialog } from './AgentFormDialog' interface AgentsSettingsProps { teamId: string } const AGENT_TYPES: { type: AgentType label: string icon: React.FC> }[] = [ { type: 'chat', label: 'Chat', icon: MessageSquare }, { type: 'autofill', label: 'Autofill', icon: Zap }, { type: 'embedding', label: 'Embedding', icon: Cpu }, ] export function AgentsSettings({ teamId }: AgentsSettingsProps) { const queryClient = useQueryClient() const { canAdmin } = usePermissions() const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false) const [createType, setCreateType] = useState('chat') const [editingAgent, setAgentToEdit] = useState(null) const [agentToDelete, setAgentToDelete] = useState(null) const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false) const [expandedSections, setExpandedSections] = useState>({ chat: true, autofill: true, embedding: true, }) const getSectionLabel = (type: AgentType) => { if (type === 'chat') return m.agent_type_chat() if (type === 'autofill') return m.agent_type_autofill() return m.agent_type_embedding() } const { data: agents = [], isLoading } = useQuery({ queryKey: ['agents', teamId], queryFn: async () => { const res = await client.api.teams[':teamId'].agents.$get({ param: { teamId }, }) if (!res.ok) throw new Error('failed to fetch agents') const data = await res.json() return [...data].sort((a, b) => b.id.localeCompare(a.id)) }, }) const deleteAgentMutation = useMutation({ mutationFn: async (agentId: string) => { const res = await client.api.agents[':agentId'].$delete({ param: { agentId }, }) if (!res.ok) throw new Error('failed to delete agent') }, onSuccess: () => { setIsDeleteDialogOpen(false) queryClient.invalidateQueries({ queryKey: ['agents', teamId] }) toast.success(m.agent_deleted_successfully()) }, onError: (error) => { toast.error(error.message) }, }) const updateAgentPermissionMutation = useMutation({ mutationFn: async ({ agentId, permission, }: { agentId: string permission: AgentPermission }) => { const res = await client.api.agents[':agentId'].permission.$patch({ param: { agentId }, json: { permission }, }) if (!res.ok) throw new Error(m.failed_to_update_permission()) return res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['agents', teamId] }) }, onError: (err: Error) => { toast.error(err.message || m.failed_to_update_permission()) }, }) const updateAgentMutation = useMutation({ mutationFn: async (params: { teamId: string agentId: string name: string type: AgentType enabled: boolean avatar?: string providerId?: string modelId?: string thinkingLevel?: ThinkingLevel systemPrompt?: string soul?: string skills?: string[] deniedTools?: string[] }) => { const res = await client.api.agents[':agentId'].$put({ param: { agentId: params.agentId }, json: { name: params.name, type: params.type, enabled: params.enabled, avatar: params.avatar, providerId: params.providerId, modelId: params.modelId, thinkingLevel: params.thinkingLevel, systemPrompt: params.systemPrompt, soul: params.soul, skills: params.skills, deniedTools: params.deniedTools, }, }) if (!res.ok) throw new Error('failed to update agent') return res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['agents', teamId] }) toast.success(m.agent_updated_successfully()) }, onError: (error) => { toast.error(error.message) }, }) const toggleSection = (type: string) => { setExpandedSections((prev) => ({ ...prev, [type]: !prev[type], })) } return ( <> {(isCreateDialogOpen || editingAgent) && ( { setIsCreateDialogOpen(false) setAgentToEdit(null) }} teamId={teamId} type={createType} initialValues={editingAgent || undefined} /> )} {m.are_you_absolutely_sure()} {m.delete_agent_confirmation({ name: agentToDelete?.name ?? '' })} {m.cancel()} { if (deleteAgentMutation.isPending) { e.preventDefault() return } if (agentToDelete) { deleteAgentMutation.mutate(agentToDelete.id) } }} > {deleteAgentMutation.isPending ? ( ) : ( m.delete_agent() )} {isLoading && agents.length === 0 ? (
) : (
{isLoading && (
)} {AGENT_TYPES.map((section) => { const typeAgents = agents.filter((a) => a.type === section.type) const Icon = section.icon const isSingleAgentType = section.type === 'autofill' || section.type === 'embedding' return (
toggleSection(section.type) : undefined} >

{section.type === 'chat' ? m.chat_agents() : section.type === 'autofill' ? m.autofill_agent() : m.embedding_agent()}

{!isSingleAgentType && ( {typeAgents.length} )}
{!(isSingleAgentType && typeAgents.length > 0) && ( )} {!isSingleAgentType && ( )}
{(isSingleAgentType || expandedSections[section.type]) && (
{typeAgents.map((agent) => ( setAgentToEdit(agent)} >
{agent.avatar ? ( ) : ( )}
{agent.name}
{m.skills_count_value({ count: agent.skills?.length || 0 })}
e.stopPropagation()}> { e.stopPropagation() setAgentToDelete(agent) setIsDeleteDialogOpen(true) }} className="text-red-500 focus:text-red-500 gap-2 cursor-pointer" > {m.delete()}
{agent.type === 'chat' ? (
e.stopPropagation()}>
) : (
)}
e.stopPropagation()}> { updateAgentMutation.mutate({ teamId, agentId: agent.id, name: agent.name, type: agent.type, enabled, avatar: agent.avatar, providerId: agent.providerId, modelId: agent.modelId, thinkingLevel: agent.thinkingLevel, systemPrompt: agent.systemPrompt, soul: agent.soul, skills: agent.skills?.map((s) => s.skillId), deniedTools: agent.deniedTools, }) }} />
))} {typeAgents.length === 0 && (

{m.no_agents_found({ type: getSectionLabel(section.type) })}

)}
)}
) })}
)} ) }