mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 11:24:43 +00:00
initial commit
This commit is contained in:
@@ -0,0 +1,487 @@
|
||||
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 '@/dtos/agent'
|
||||
import { Textarea } from '@/ui/components/ui/textarea'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { z } from 'zod'
|
||||
|
||||
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', 'transcription']),
|
||||
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<typeof agentFormSchema>
|
||||
|
||||
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 || '',
|
||||
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.teams[':teamId'].providers[':id'].models.$get({
|
||||
param: { teamId, 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.teams[':teamId'].agents[':agentId'].$put({
|
||||
param: { teamId, 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 (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="sm:max-w-3xl h-[90vh] flex flex-col p-0 overflow-hidden">
|
||||
<DialogHeader className="p-6 pb-2 flex-shrink-0">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure your AI agent's personality and capabilities.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
form.handleSubmit()
|
||||
}}
|
||||
className="flex-1 flex flex-col min-h-0 overflow-hidden"
|
||||
>
|
||||
<ScrollArea className="flex-1 h-full">
|
||||
<div className="p-6 pt-2 space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<form.Field
|
||||
name="name"
|
||||
children={(field) => {
|
||||
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel>Agent Name</FieldLabel>
|
||||
<Input
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
placeholder="e.g., Support Assistant"
|
||||
aria-invalid={isInvalid}
|
||||
/>
|
||||
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
|
||||
<form.Field
|
||||
name="type"
|
||||
children={(field) => (
|
||||
<Field>
|
||||
<FieldLabel>Agent Type</FieldLabel>
|
||||
<Select
|
||||
value={field.state.value}
|
||||
onValueChange={(val) => field.handleChange(val as AgentType)}
|
||||
disabled={true}
|
||||
>
|
||||
<SelectTrigger className="bg-slate-50 dark:bg-slate-900/50">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="chat">Chat</SelectItem>
|
||||
<SelectItem value="autofill">Autofill</SelectItem>
|
||||
<SelectItem value="embedding">Embedding</SelectItem>
|
||||
<SelectItem value="transcription">Transcription</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isAiType && (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 bg-slate-50 dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800">
|
||||
<form.Field
|
||||
name="providerId"
|
||||
children={(field) => {
|
||||
const isInvalid =
|
||||
!!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel>Provider</FieldLabel>
|
||||
<Select
|
||||
value={field.state.value}
|
||||
onValueChange={(val) => {
|
||||
field.handleChange(val)
|
||||
form.setFieldValue('modelId', '')
|
||||
}}
|
||||
>
|
||||
<SelectTrigger aria-invalid={isInvalid}>
|
||||
<SelectValue placeholder="Select Provider" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{providers?.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{isInvalid && (
|
||||
<FieldError errors={mapErrors(field.state.meta.errors)} />
|
||||
)}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
|
||||
<form.Field
|
||||
name="modelId"
|
||||
children={(field) => {
|
||||
const isInvalid =
|
||||
!!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel className="flex items-center gap-2">
|
||||
Model
|
||||
{isModelsLoading && <Loader2 className="w-3 h-3 animate-spin" />}
|
||||
</FieldLabel>
|
||||
<Select
|
||||
value={field.state.value}
|
||||
onValueChange={field.handleChange}
|
||||
disabled={!selectedProviderId || isModelsLoading}
|
||||
>
|
||||
<SelectTrigger aria-invalid={isInvalid}>
|
||||
<SelectValue placeholder="Select Model" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{models?.map((m) => (
|
||||
<SelectItem key={m.id} value={m.id}>
|
||||
{m.name || m.modelId}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{isInvalid && (
|
||||
<FieldError errors={mapErrors(field.state.meta.errors)} />
|
||||
)}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<form.Field
|
||||
name="thinkingLevel"
|
||||
children={(field) => (
|
||||
<Field>
|
||||
<FieldLabel>Thinking Level</FieldLabel>
|
||||
<Select value={field.state.value} onValueChange={field.handleChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="low">Low (Fast)</SelectItem>
|
||||
<SelectItem value="medium">Medium (Balanced)</SelectItem>
|
||||
<SelectItem value="high">High (Reasoning)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form.Field
|
||||
name="soul"
|
||||
children={(field) => (
|
||||
<Field>
|
||||
<FieldLabel>Agent Soul (Personality)</FieldLabel>
|
||||
<Textarea
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
placeholder="Describe the agent's personality, tone, and behavior..."
|
||||
className="min-h-[120px]"
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Label className="text-base font-bold flex items-center gap-2">
|
||||
<Puzzle className="w-5 h-5 text-blue-600" />
|
||||
Skills
|
||||
</Label>
|
||||
|
||||
<div className="space-y-2">
|
||||
<form.Field
|
||||
name="skills"
|
||||
children={(skillsField) => (
|
||||
<>
|
||||
{allSkills.map((skill) => {
|
||||
const isEnabled = skillsField.state.value?.includes(skill.id) || false
|
||||
return (
|
||||
<div
|
||||
key={skill.id}
|
||||
className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Puzzle className="w-4 h-4 text-slate-400" />
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-medium">{skill.name}</span>
|
||||
{skill.description && (
|
||||
<span className="text-[10px] text-slate-500 line-clamp-1">
|
||||
{skill.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-slate-500">
|
||||
{isEnabled ? 'Enabled' : 'Disabled'}
|
||||
</span>
|
||||
<Switch
|
||||
checked={isEnabled}
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked) {
|
||||
skillsField.handleChange([
|
||||
...(skillsField.state.value || []),
|
||||
skill.id,
|
||||
])
|
||||
} else {
|
||||
skillsField.handleChange(
|
||||
(skillsField.state.value || []).filter(
|
||||
(id) => id !== skill.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{allSkills.length === 0 && (
|
||||
<div className="text-center py-8 border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-xl">
|
||||
<p className="text-sm text-slate-400">No skills available.</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter className="p-6 pt-4 border-t dark:border-slate-800 flex-shrink-0">
|
||||
<Button variant="outline" onClick={onClose} type="button">
|
||||
Cancel
|
||||
</Button>
|
||||
<form.Subscribe
|
||||
selector={(state) => [state.canSubmit, state.isSubmitting]}
|
||||
children={([canSubmit, isSubmitting]) => (
|
||||
<Button
|
||||
type="submit"
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white min-w-[120px]"
|
||||
disabled={
|
||||
!canSubmit ||
|
||||
isSubmitting ||
|
||||
createMutation.isPending ||
|
||||
updateMutation.isPending
|
||||
}
|
||||
>
|
||||
{(isSubmitting || createMutation.isPending || updateMutation.isPending) && (
|
||||
<Loader2 className="w-4 h-4 animate-spin mr-2" />
|
||||
)}
|
||||
{initialValues ? 'Save Changes' : 'Create Agent'}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Card, CardContent } from '@/ui/components/ui/card'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Loader2,
|
||||
Plus,
|
||||
Trash2,
|
||||
Bot,
|
||||
MoreVertical,
|
||||
MessageSquare,
|
||||
Zap,
|
||||
Cpu,
|
||||
Type,
|
||||
Puzzle,
|
||||
} from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { AgentInfo, AgentType } from '@/dtos/agent'
|
||||
import { AgentFormDialog } from './AgentFormDialog'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
|
||||
interface AgentsSettingsProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
const AGENT_TYPES: {
|
||||
type: AgentType
|
||||
label: string
|
||||
icon: React.FC<React.SVGProps<SVGSVGElement>>
|
||||
}[] = [
|
||||
{ type: 'chat', label: 'Chat', icon: MessageSquare },
|
||||
{ type: 'autofill', label: 'Autofill', icon: Zap },
|
||||
{ type: 'embedding', label: 'Embedding', icon: Cpu },
|
||||
{ type: 'transcription', label: 'Transcription', icon: Type },
|
||||
]
|
||||
|
||||
export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
|
||||
const [createType, setCreateType] = useState<AgentType>('chat')
|
||||
const [editingAgent, setAgentToEdit] = useState<AgentInfo | null>(null)
|
||||
const [agentToDelete, setAgentToDelete] = useState<AgentInfo | null>(null)
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
|
||||
chat: true,
|
||||
autofill: true,
|
||||
embedding: true,
|
||||
transcription: true,
|
||||
})
|
||||
|
||||
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.teams[':teamId'].agents[':agentId'].$delete({
|
||||
param: { teamId, agentId },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to delete agent')
|
||||
},
|
||||
onSuccess: () => {
|
||||
setIsDeleteDialogOpen(false)
|
||||
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
|
||||
toast.success('Agent deleted successfully')
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error.message)
|
||||
},
|
||||
})
|
||||
|
||||
const updateAgentMutation = useMutation({
|
||||
mutationFn: async (params: {
|
||||
teamId: string
|
||||
agentId: string
|
||||
name: string
|
||||
type: AgentType
|
||||
enabled: boolean
|
||||
avatar?: string
|
||||
providerId?: string
|
||||
modelId?: string
|
||||
thinkingLevel?: string
|
||||
systemPrompt?: string
|
||||
soul?: string
|
||||
skills?: string[]
|
||||
}) => {
|
||||
const res = await client.api.teams[':teamId'].agents[':agentId'].$put({
|
||||
param: { teamId: params.teamId, 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,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to update agent')
|
||||
return res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['agents', teamId] })
|
||||
toast.success('Agent updated successfully')
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error.message)
|
||||
},
|
||||
})
|
||||
|
||||
const toggleSection = (type: string) => {
|
||||
setExpandedSections((prev) => ({
|
||||
...prev,
|
||||
[type]: !prev[type],
|
||||
}))
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{(isCreateDialogOpen || editingAgent) && (
|
||||
<AgentFormDialog
|
||||
isOpen={true}
|
||||
title={editingAgent ? `Edit ${editingAgent.name}` : `Create ${createType} Agent`}
|
||||
onClose={() => {
|
||||
setIsCreateDialogOpen(false)
|
||||
setAgentToEdit(null)
|
||||
}}
|
||||
teamId={teamId}
|
||||
type={createType}
|
||||
initialValues={editingAgent || undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This action cannot be undone. This will permanently delete the agent "
|
||||
{agentToDelete?.name}" and remove all its data from our servers.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
onClick={(e) => {
|
||||
if (deleteAgentMutation.isPending) {
|
||||
e.preventDefault()
|
||||
return
|
||||
}
|
||||
if (agentToDelete) {
|
||||
deleteAgentMutation.mutate(agentToDelete.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{deleteAgentMutation.isPending ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
'Delete Agent'
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{isLoading && agents.length === 0 ? (
|
||||
<div className="flex items-center justify-center p-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-slate-400" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6 max-w-5xl mx-auto relative">
|
||||
{isLoading && (
|
||||
<div className="absolute top-0 right-0 p-2">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-slate-400" />
|
||||
</div>
|
||||
)}
|
||||
{AGENT_TYPES.map((section) => {
|
||||
const typeAgents = agents.filter((a) => a.type === section.type)
|
||||
const Icon = section.icon
|
||||
|
||||
return (
|
||||
<div
|
||||
key={section.type}
|
||||
className="bg-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-slate-800 overflow-hidden"
|
||||
>
|
||||
<div
|
||||
className="px-6 py-4 flex items-center justify-between cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors"
|
||||
onClick={() => toggleSection(section.type)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="font-semibold text-slate-900 dark:text-white">
|
||||
{section.label} Agents
|
||||
</h3>
|
||||
<Badge variant="secondary" className="h-5 px-1.5 min-w-[1.25rem] text-[10px]">
|
||||
{typeAgents.length}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{!(
|
||||
(section.type === 'autofill' ||
|
||||
section.type === 'transcription' ||
|
||||
section.type === 'embedding') &&
|
||||
typeAgents.length > 0
|
||||
) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/40"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setCreateType(section.type)
|
||||
setIsCreateDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'w-5 h-5 text-slate-400 transition-transform duration-200',
|
||||
expandedSections[section.type] ? 'rotate-180' : '',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{expandedSections[section.type] && (
|
||||
<div className="px-6 pb-6 pt-2 space-y-3">
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
{typeAgents.map((agent) => (
|
||||
<Card
|
||||
key={agent.id}
|
||||
className="group relative overflow-hidden border-slate-200 dark:border-slate-800 hover:border-blue-500/50 dark:hover:border-blue-400/50 transition-all duration-200 cursor-pointer"
|
||||
onClick={() => setAgentToEdit(agent)}
|
||||
>
|
||||
<CardContent className="p-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3 min-w-0 flex-1">
|
||||
<div className="w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center overflow-hidden">
|
||||
{agent.avatar ? (
|
||||
<img
|
||||
src={agent.avatar}
|
||||
className="w-full h-full object-cover"
|
||||
alt=""
|
||||
/>
|
||||
) : (
|
||||
<Bot className="w-6 h-6 text-slate-400" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="font-bold text-slate-900 dark:text-white block truncate">
|
||||
{agent.name}
|
||||
</span>
|
||||
<div className="flex items-center gap-2 text-xs text-slate-500 mt-0.5">
|
||||
<span className="flex items-center gap-1">
|
||||
<Puzzle className="w-3 h-3" />
|
||||
{agent.skills?.length || 0} Skills
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="mr-2" onClick={(e) => e.stopPropagation()}>
|
||||
<Switch
|
||||
checked={agent.enabled}
|
||||
onCheckedChange={(enabled) => {
|
||||
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),
|
||||
})
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300"
|
||||
>
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-32">
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setAgentToDelete(agent)
|
||||
setIsDeleteDialogOpen(true)
|
||||
}}
|
||||
className="text-red-500 focus:text-red-500 gap-2 cursor-pointer"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" /> Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>{' '}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
{typeAgents.length === 0 && (
|
||||
<div className="col-span-full py-8 flex flex-col items-center justify-center border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-xl bg-slate-50/50 dark:bg-slate-900/20">
|
||||
<div className="w-10 h-10 rounded-full bg-white dark:bg-slate-800 flex items-center justify-center shadow-sm mb-3">
|
||||
<Icon className="w-5 h-5 text-slate-400" />
|
||||
</div>
|
||||
<p className="text-sm text-slate-500">No {section.label} agents found</p>
|
||||
<Button
|
||||
variant="link"
|
||||
size="sm"
|
||||
className="text-blue-600 font-medium h-auto p-0 mt-1"
|
||||
onClick={() => {
|
||||
setCreateType(section.type)
|
||||
setIsCreateDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
Create one now
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { Switch as ShadcnSwitch } from '@/ui/components/ui/switch'
|
||||
import { Textarea } from '@/ui/components/ui/textarea'
|
||||
import React from 'react'
|
||||
import { PROVIDERS } from './constants'
|
||||
import { ThinkingLevel } from './types'
|
||||
|
||||
// --- Section Header ---
|
||||
export const SectionLabel: React.FC<{
|
||||
label: string
|
||||
subLabel?: string
|
||||
htmlFor?: string
|
||||
}> = ({ label, subLabel, htmlFor }) => (
|
||||
<div className="mb-2">
|
||||
<Label htmlFor={htmlFor} className="block text-sm font-medium">
|
||||
{label}
|
||||
</Label>
|
||||
{subLabel && <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">{subLabel}</p>}
|
||||
</div>
|
||||
)
|
||||
|
||||
// --- Text Input ---
|
||||
interface TextInputProps extends React.ComponentProps<typeof Input> {
|
||||
label: string
|
||||
}
|
||||
|
||||
export const TextInput: React.FC<TextInputProps> = ({ label, className = '', id, ...props }) => (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={id}>{label}</Label>
|
||||
<Input className={className} id={id} {...props} />
|
||||
</div>
|
||||
)
|
||||
|
||||
// --- Agent Type Selector ---
|
||||
export const AgentTypeSelector: React.FC<{
|
||||
value: 'chat' | 'autofill'
|
||||
onChange: (val: 'chat' | 'autofill') => void
|
||||
}> = ({ value, onChange }) => {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<SectionLabel label="Agent Type" />
|
||||
<Select value={value} onValueChange={(val: 'chat' | 'autofill') => onChange(val)}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Select type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="chat">Chat Agent</SelectItem>
|
||||
<SelectItem value="autofill">Autofill Agent</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Text Area ---
|
||||
interface TextAreaProps extends React.ComponentProps<typeof Textarea> {
|
||||
label: string
|
||||
subLabel?: string
|
||||
}
|
||||
|
||||
export const TextArea: React.FC<TextAreaProps> = ({
|
||||
label,
|
||||
subLabel,
|
||||
className = '',
|
||||
id,
|
||||
...props
|
||||
}) => (
|
||||
<div className="space-y-2">
|
||||
<SectionLabel label={label} subLabel={subLabel} htmlFor={id} />
|
||||
<Textarea className={`resize-y min-h-[100px] ${className}`} id={id} {...props} />
|
||||
</div>
|
||||
)
|
||||
|
||||
// --- Provider & Model Selector ---
|
||||
interface ModelSelectorProps {
|
||||
provider: string | undefined
|
||||
model: string | undefined
|
||||
models: string[]
|
||||
onProviderChange: (p: string) => void
|
||||
onModelChange: (m: string) => void
|
||||
label?: string // Optional custom label
|
||||
subLabel?: string
|
||||
}
|
||||
|
||||
export const ModelSelector: React.FC<ModelSelectorProps> = ({
|
||||
provider,
|
||||
model,
|
||||
models,
|
||||
onProviderChange,
|
||||
onModelChange,
|
||||
label = 'AI Provider',
|
||||
subLabel,
|
||||
}) => {
|
||||
return (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<SectionLabel label={label} subLabel={subLabel} />
|
||||
<Select value={provider || ''} onValueChange={(val) => onProviderChange(val)}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Select provider" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{PROVIDERS.map((p) => (
|
||||
<SelectItem key={p.value} value={p.value}>
|
||||
{p.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<SectionLabel label="Model" />
|
||||
<Select value={model || ''} onValueChange={(val) => onModelChange(val)}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Select model" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{models.length > 0 ? (
|
||||
models.map((m) => (
|
||||
<SelectItem key={m} value={m}>
|
||||
{m}
|
||||
</SelectItem>
|
||||
))
|
||||
) : (
|
||||
<SelectItem value="none" disabled>
|
||||
No models configured
|
||||
</SelectItem>
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Thinking Level Selector ---
|
||||
interface ThinkingLevelSelectorProps {
|
||||
value: ThinkingLevel | string | undefined
|
||||
onChange: (val: ThinkingLevel) => void
|
||||
disabled?: boolean
|
||||
label?: string
|
||||
}
|
||||
|
||||
export const ThinkingLevelSelector: React.FC<ThinkingLevelSelectorProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
label = 'Thinking Strength',
|
||||
}) => {
|
||||
const levels = [
|
||||
{
|
||||
id: ThinkingLevel.DISABLED,
|
||||
label: 'Disable',
|
||||
desc: 'Standard generation',
|
||||
},
|
||||
{ id: ThinkingLevel.LOW, label: 'Low', desc: 'Quick reasoning' },
|
||||
{ id: ThinkingLevel.MEDIUM, label: 'Medium', desc: 'Balanced thought' },
|
||||
{ id: ThinkingLevel.HIGH, label: 'High', desc: 'Deep reasoning' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className={disabled ? 'opacity-50 pointer-events-none grayscale' : ''}>
|
||||
<SectionLabel label={label} subLabel="Control the depth of reasoning for complex tasks." />
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
||||
{levels.map((level) => {
|
||||
const isSelected = value === level.id
|
||||
return (
|
||||
<button
|
||||
key={level.id}
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
onChange(level.id)
|
||||
}}
|
||||
className={`flex flex-col items-center justify-center p-3 rounded-lg border transition-all duration-200 ${
|
||||
isSelected
|
||||
? 'bg-blue-50 dark:bg-blue-900/30 border-blue-500 dark:border-blue-400 text-blue-700 dark:text-blue-300 ring-1 ring-blue-500 dark:ring-blue-400'
|
||||
: 'bg-white dark:bg-slate-950 border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:border-slate-300 dark:hover:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-900'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`text-sm font-semibold ${isSelected ? 'text-blue-700 dark:text-blue-300' : 'text-slate-900 dark:text-white'}`}
|
||||
>
|
||||
{level.label}
|
||||
</span>
|
||||
<span
|
||||
className={`text-[10px] mt-1 ${isSelected ? 'text-blue-600 dark:text-blue-400' : 'text-slate-500 dark:text-slate-500'}`}
|
||||
>
|
||||
{level.desc}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Toggle Switch ---
|
||||
interface SwitchProps {
|
||||
label: string
|
||||
description?: string
|
||||
checked: boolean | undefined // Handle optional/undefined from API
|
||||
onChange: (checked: boolean) => void
|
||||
}
|
||||
|
||||
export const Switch: React.FC<SwitchProps> = ({ label, description, checked, onChange }) => {
|
||||
const isChecked = !!checked
|
||||
return (
|
||||
<div className="flex flex-row items-center justify-between rounded-lg border p-4 shadow-sm">
|
||||
<div className="space-y-0.5">
|
||||
<Label className="text-base cursor-pointer" onClick={() => onChange(!isChecked)}>
|
||||
{label}
|
||||
</Label>
|
||||
{description && <p className="text-sm text-muted-foreground">{description}</p>}
|
||||
</div>
|
||||
<ShadcnSwitch checked={isChecked} onCheckedChange={onChange} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,946 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Card, CardContent } from '@/ui/components/ui/card'
|
||||
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, FieldDescription, 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 { Badge } from '@/ui/components/ui/badge'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useForm } from '@tanstack/react-form'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
Loader2,
|
||||
Plus,
|
||||
Trash2,
|
||||
Cpu,
|
||||
Globe,
|
||||
ChevronRight,
|
||||
Info,
|
||||
DollarSign,
|
||||
Maximize2,
|
||||
Zap,
|
||||
Search,
|
||||
MoreVertical,
|
||||
} from 'lucide-react'
|
||||
import { useState, useMemo, useEffect } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { InferResponseType } from 'hono/client'
|
||||
import { providerConfigSchema, providerModelSchema } from '@/dtos/provider'
|
||||
import { z } from 'zod'
|
||||
|
||||
const providerFormSchemaBase = z.object({
|
||||
name: z.string().min(1, 'Provider name is required'),
|
||||
config: providerConfigSchema,
|
||||
models: z.array(providerModelSchema).min(1, 'At least one model is required'),
|
||||
})
|
||||
|
||||
type ProviderFormValues = z.infer<typeof providerFormSchemaBase>
|
||||
|
||||
type ProvidersResponse = InferResponseType<
|
||||
(typeof client.api.teams)[':teamId']['providers']['$get']
|
||||
>
|
||||
type Provider = ProvidersResponse[number]
|
||||
|
||||
interface ProvidersSettingsProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [editingProviderId, setEditingProviderId] = useState<string | null>(null)
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const [providerToDelete, setProviderToDelete] = useState<Provider | null>(null)
|
||||
|
||||
// Fetch Providers
|
||||
const { data: providers, isLoading } = 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()
|
||||
},
|
||||
})
|
||||
|
||||
const editingProvider = useMemo(
|
||||
() => providers?.find((p) => p.id === editingProviderId) || null,
|
||||
[providers, editingProviderId],
|
||||
)
|
||||
|
||||
// Fetch models for editing
|
||||
const { data: editingModels, isLoading: isModelsLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'providers', editingProviderId, 'models'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].providers[':id'].models.$get({
|
||||
param: { teamId, id: editingProviderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch models')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!editingProviderId,
|
||||
})
|
||||
|
||||
const existingProviderNames = useMemo(() => providers?.map((p) => p.name) || [], [providers])
|
||||
|
||||
const filteredProviders = useMemo(() => {
|
||||
if (!providers) return []
|
||||
if (!searchQuery.trim()) return providers
|
||||
const query = searchQuery.toLowerCase()
|
||||
return providers.filter((p) => p.name.toLowerCase().includes(query))
|
||||
}, [providers, searchQuery])
|
||||
|
||||
// Create Mutation
|
||||
const createMutation = useMutation({
|
||||
mutationFn: async (values: ProviderFormValues) => {
|
||||
const res = await client.api.teams[':teamId'].providers.$post({
|
||||
param: { teamId },
|
||||
json: {
|
||||
name: values.name,
|
||||
config: values.config,
|
||||
models: values.models,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to create provider')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
setIsCreateDialogOpen(false)
|
||||
toast.success('Provider created successfully')
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Error: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
// Update Mutation
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: async ({ id, values }: { id: string; values: ProviderFormValues }) => {
|
||||
const res = await client.api.teams[':teamId'].providers[':id'].$put({
|
||||
param: { teamId, id },
|
||||
json: {
|
||||
config: values.config,
|
||||
models: values.models,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update provider')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
setEditingProviderId(null)
|
||||
toast.success('Provider updated successfully')
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Error: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
// Delete Mutation
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const res = await client.api.teams[':teamId'].providers[':id'].$delete({
|
||||
param: { teamId, id },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to delete provider')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'providers'] })
|
||||
setEditingProviderId(null)
|
||||
setIsDeleteDialogOpen(false)
|
||||
setProviderToDelete(null)
|
||||
toast.success('Provider deleted successfully')
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(`Error: ${error.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-64 items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-blue-600" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col space-y-0">
|
||||
<div className="flex-none space-y-4 pb-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-slate-900 dark:text-white flex items-center gap-2">
|
||||
<Cpu className="w-5 h-5 text-blue-600" />
|
||||
Configured AI Providers
|
||||
</h3>
|
||||
<Button
|
||||
onClick={() => setIsCreateDialogOpen(true)}
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white gap-2"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add Provider
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="relative px-0.5">
|
||||
<Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
|
||||
<Input
|
||||
placeholder="Search providers..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-10 bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto pr-2 min-h-0 overflow-x-hidden">
|
||||
<div className="grid grid-cols-1 gap-4 py-2">
|
||||
{filteredProviders.map((provider) => (
|
||||
<Card
|
||||
key={provider.id}
|
||||
className="group cursor-pointer hover:border-blue-300 dark:hover:border-blue-700 transition-all hover:shadow-md overflow-hidden"
|
||||
onClick={() => setEditingProviderId(provider.id)}
|
||||
>
|
||||
<CardContent className="p-5 flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-4 min-w-0 flex-1">
|
||||
<div className="flex-none p-3 bg-slate-100 dark:bg-slate-800 rounded-xl group-hover:bg-blue-50 dark:group-hover:bg-blue-900/20 transition-colors">
|
||||
<Globe className="w-6 h-6 text-slate-600 dark:text-slate-400 group-hover:text-blue-600 dark:group-hover:text-blue-400" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-bold text-slate-900 dark:text-white truncate">
|
||||
{provider.name}
|
||||
</span>
|
||||
{provider.isBuiltin && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="flex-none text-[10px] uppercase tracking-wider font-bold h-5"
|
||||
>
|
||||
Built-in
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs text-slate-500 mt-1">
|
||||
<span className="flex items-center gap-1 flex-none">
|
||||
<Zap className="w-3 h-3" />
|
||||
{provider.config.api}
|
||||
</span>
|
||||
{provider.config.baseUrl && (
|
||||
<span className="flex items-center gap-1 min-w-0">
|
||||
<span className="h-1 w-1 rounded-full bg-slate-300 dark:bg-slate-700 flex-none" />
|
||||
<Info className="w-3 h-3 flex-none" />
|
||||
<span className="truncate max-w-[200px] md:max-w-[300px]">
|
||||
{provider.config.baseUrl}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1 flex-none">
|
||||
<span className="h-1 w-1 rounded-full bg-slate-300 dark:bg-slate-700 flex-none" />
|
||||
<Maximize2 className="w-3 h-3" />
|
||||
{provider.modelsCount} Models
|
||||
{editingProviderId === provider.id && isModelsLoading && (
|
||||
<Loader2 className="w-3 h-3 animate-spin ml-1" />
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300"
|
||||
>
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-32">
|
||||
<DropdownMenuItem
|
||||
disabled={provider.isBuiltin}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setProviderToDelete(provider)
|
||||
setIsDeleteDialogOpen(true)
|
||||
}}
|
||||
className="text-red-500 focus:text-red-500 gap-2 cursor-pointer"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" /> Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ChevronRight className="flex-none w-5 h-5 text-slate-300 group-hover:text-blue-500 transition-colors" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{providers?.length === 0 && (
|
||||
<div className="text-center py-12 bg-slate-50 dark:bg-slate-900/50 rounded-2xl border-2 border-dashed border-slate-200 dark:border-slate-800">
|
||||
<Cpu className="w-12 h-12 text-slate-300 mx-auto mb-4" />
|
||||
<h4 className="text-slate-900 dark:text-white font-medium">
|
||||
No Providers Configured
|
||||
</h4>
|
||||
<p className="text-sm text-slate-500 mt-1">
|
||||
Add your first AI provider to get started.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{providers && providers.length > 0 && filteredProviders.length === 0 && (
|
||||
<div className="text-center py-12">
|
||||
<Search className="w-12 h-12 text-slate-300 mx-auto mb-4" />
|
||||
<h4 className="text-slate-900 dark:text-white font-medium">No matches found</h4>
|
||||
<p className="text-sm text-slate-500 mt-1">
|
||||
Try adjusting your search for "{searchQuery}"
|
||||
</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
className="mt-4 text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:hover:bg-blue-900/20"
|
||||
>
|
||||
Clear search
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ProviderFormDialog
|
||||
isOpen={isCreateDialogOpen}
|
||||
onClose={() => setIsCreateDialogOpen(false)}
|
||||
onSubmit={(values) => createMutation.mutate(values)}
|
||||
isLoading={createMutation.isPending}
|
||||
title="Add New Provider"
|
||||
existingProviderNames={existingProviderNames}
|
||||
/>
|
||||
|
||||
<ProviderFormDialog
|
||||
isOpen={!!editingProvider && !isModelsLoading && !!editingModels}
|
||||
onClose={() => setEditingProviderId(null)}
|
||||
onSubmit={(values) => updateMutation.mutate({ id: editingProvider!.id, values })}
|
||||
onDelete={() => deleteMutation.mutate(editingProvider!.id)}
|
||||
isLoading={updateMutation.isPending || deleteMutation.isPending}
|
||||
initialValues={
|
||||
editingProvider && editingModels
|
||||
? {
|
||||
name: editingProvider.name,
|
||||
config: editingProvider.config,
|
||||
models: editingModels,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
isBuiltin={editingProvider?.isBuiltin}
|
||||
title={`Edit ${editingProvider?.name}`}
|
||||
existingProviderNames={existingProviderNames}
|
||||
/>
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This action cannot be undone. This will permanently delete the provider "
|
||||
{providerToDelete?.name}" and all associated model configurations.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={() => setProviderToDelete(null)}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-red-600 hover:bg-red-700 text-white"
|
||||
onClick={() => {
|
||||
if (providerToDelete) {
|
||||
deleteMutation.mutate(providerToDelete.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{deleteMutation.isPending ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin mr-2" />
|
||||
) : (
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface ProviderFormDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onSubmit: (values: ProviderFormValues) => void
|
||||
onDelete?: () => void
|
||||
isLoading: boolean
|
||||
initialValues?: ProviderFormValues
|
||||
isBuiltin?: boolean
|
||||
title: string
|
||||
existingProviderNames: string[]
|
||||
}
|
||||
|
||||
function ProviderFormDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSubmit,
|
||||
onDelete,
|
||||
isLoading,
|
||||
initialValues,
|
||||
isBuiltin,
|
||||
title,
|
||||
existingProviderNames,
|
||||
}: ProviderFormDialogProps) {
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const schema = useMemo(() => {
|
||||
return providerFormSchemaBase.extend({
|
||||
name: z
|
||||
.string()
|
||||
.min(1, 'Provider name is required')
|
||||
.refine(
|
||||
(name) => {
|
||||
if (initialValues?.name === name) return true
|
||||
return !existingProviderNames.includes(name)
|
||||
},
|
||||
{ message: 'Provider name must be unique' },
|
||||
),
|
||||
})
|
||||
}, [existingProviderNames, initialValues])
|
||||
|
||||
const form = useForm({
|
||||
defaultValues: (initialValues || {
|
||||
name: '',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
baseUrl: '',
|
||||
apiKey: '',
|
||||
},
|
||||
models: [
|
||||
{
|
||||
modelId: '',
|
||||
name: '',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
}) as z.input<typeof schema>,
|
||||
validators: {
|
||||
onChange: schema,
|
||||
},
|
||||
onSubmit: async ({ value }) => {
|
||||
onSubmit(value as ProviderFormValues)
|
||||
},
|
||||
})
|
||||
|
||||
// Reset form when dialog opens
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
form.reset()
|
||||
}
|
||||
}, [isOpen, form])
|
||||
|
||||
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 (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="sm:max-w-4xl max-h-[90vh] flex flex-col p-0 overflow-hidden">
|
||||
<DialogHeader className="p-6 pb-2">
|
||||
<DialogTitle className="text-xl">{title}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure authentication and model details for your AI provider.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
form.handleSubmit()
|
||||
}}
|
||||
className="flex flex-col flex-1 overflow-hidden"
|
||||
>
|
||||
<div className="flex-1 overflow-y-auto p-6 pt-2 space-y-8">
|
||||
{/* Row 1: Basic Config */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-6 bg-slate-50 dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800">
|
||||
<form.Field
|
||||
name="name"
|
||||
children={(field) => {
|
||||
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel htmlFor={field.name}>Provider Name</FieldLabel>
|
||||
<Input
|
||||
id={field.name}
|
||||
name={field.name}
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
placeholder="e.g., My OpenAI"
|
||||
disabled={isBuiltin}
|
||||
aria-invalid={isInvalid}
|
||||
/>
|
||||
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
|
||||
<form.Field
|
||||
name="config.api"
|
||||
children={(field) => {
|
||||
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel htmlFor={field.name}>Global API Protocol</FieldLabel>
|
||||
<Select
|
||||
onValueChange={field.handleChange}
|
||||
value={field.state.value}
|
||||
disabled={isBuiltin}
|
||||
>
|
||||
<SelectTrigger id={field.name} aria-invalid={isInvalid}>
|
||||
<SelectValue placeholder="Select API Protocol" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="openai-completions">OpenAI Completions</SelectItem>
|
||||
<SelectItem value="anthropic-messages">Anthropic Messages</SelectItem>
|
||||
<SelectItem value="google-genai">Google GenAI</SelectItem>
|
||||
<SelectItem value="bedrock-converse-stream">AWS Bedrock</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<form.Field
|
||||
name="config.baseUrl"
|
||||
children={(field) => {
|
||||
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel htmlFor={field.name}>Base URL (Optional)</FieldLabel>
|
||||
<Input
|
||||
id={field.name}
|
||||
name={field.name}
|
||||
value={field.state.value || ''}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
placeholder="https://api.openai.com/v1"
|
||||
aria-invalid={isInvalid}
|
||||
/>
|
||||
<FieldDescription>Override the default endpoint.</FieldDescription>
|
||||
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Row 2: API Key Card */}
|
||||
<Card className="bg-slate-50 dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800">
|
||||
<CardContent className="p-6">
|
||||
<form.Field
|
||||
name="config.apiKey"
|
||||
children={(field) => {
|
||||
const isInvalid = !!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel htmlFor={field.name} className="text-base font-semibold">
|
||||
API Key
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id={field.name}
|
||||
name={field.name}
|
||||
type="text"
|
||||
value={field.state.value || ''}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
placeholder="Enter API Key or Environment Variable"
|
||||
aria-invalid={isInvalid}
|
||||
/>
|
||||
<FieldDescription className="text-xs mt-2">
|
||||
You can provide a literal value (e.g.{' '}
|
||||
<code className="bg-slate-200 dark:bg-slate-800 px-1 rounded text-blue-600 dark:text-blue-400">
|
||||
sk-...
|
||||
</code>
|
||||
) or an Environment variable name (e.g.{' '}
|
||||
<code className="bg-slate-200 dark:bg-slate-800 px-1 rounded text-blue-600 dark:text-blue-400">
|
||||
MY_API_KEY
|
||||
</code>
|
||||
).
|
||||
</FieldDescription>
|
||||
{isInvalid && <FieldError errors={mapErrors(field.state.meta.errors)} />}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Models Section */}
|
||||
<div className="space-y-4">
|
||||
<form.Field
|
||||
name="models"
|
||||
mode="array"
|
||||
children={(modelsField) => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-lg font-bold">Models Configuration</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
modelsField.pushValue({
|
||||
modelId: '',
|
||||
name: '',
|
||||
config: {
|
||||
api: form.getFieldValue('config.api'),
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
})
|
||||
}
|
||||
className="gap-2"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add Model
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{modelsField.state.value.map((_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="group relative p-6 bg-white dark:bg-slate-950 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm animate-in fade-in zoom-in-95 duration-300"
|
||||
>
|
||||
{/* Row 1: ID and Name */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<form.Field
|
||||
name={`models[${index}].modelId`}
|
||||
children={(field) => {
|
||||
const isInvalid =
|
||||
!!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel htmlFor={field.name}>Model ID</FieldLabel>
|
||||
<Input
|
||||
id={field.name}
|
||||
name={field.name}
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
placeholder="gpt-4o"
|
||||
aria-invalid={isInvalid}
|
||||
/>
|
||||
{isInvalid && (
|
||||
<FieldError errors={mapErrors(field.state.meta.errors)} />
|
||||
)}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<form.Field
|
||||
name={`models[${index}].name`}
|
||||
children={(field) => {
|
||||
const isInvalid =
|
||||
!!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel htmlFor={field.name}>
|
||||
Display Name (Optional)
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id={field.name}
|
||||
name={field.name}
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) => field.handleChange(e.target.value)}
|
||||
placeholder="e.g., GPT-4o"
|
||||
aria-invalid={isInvalid}
|
||||
disabled={isBuiltin}
|
||||
/>
|
||||
{isInvalid && (
|
||||
<FieldError errors={mapErrors(field.state.meta.errors)} />
|
||||
)}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Row 2: Reasoning and Context Window */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
|
||||
<form.Field
|
||||
name={`models[${index}].config.reasoning`}
|
||||
children={(field) => (
|
||||
<Field
|
||||
orientation="horizontal"
|
||||
className="rounded-lg border p-3 shadow-sm bg-slate-50 dark:bg-slate-900 justify-between"
|
||||
>
|
||||
<FieldLabel htmlFor={field.name}>Reasoning Support</FieldLabel>
|
||||
<Switch
|
||||
id={field.name}
|
||||
checked={field.state.value}
|
||||
onCheckedChange={field.handleChange}
|
||||
disabled={isBuiltin}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
/>
|
||||
<form.Field
|
||||
name={`models[${index}].config.contextWindow`}
|
||||
children={(field) => {
|
||||
const isInvalid =
|
||||
!!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel htmlFor={field.name} className="text-xs">
|
||||
Context Window (tokens)
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id={field.name}
|
||||
name={field.name}
|
||||
type="number"
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) =>
|
||||
field.handleChange(parseInt(e.target.value) || 0)
|
||||
}
|
||||
aria-invalid={isInvalid}
|
||||
disabled={isBuiltin}
|
||||
/>
|
||||
{isInvalid && (
|
||||
<FieldError errors={mapErrors(field.state.meta.errors)} />
|
||||
)}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Row 3: Constraints and Cost */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
|
||||
<form.Field
|
||||
name={`models[${index}].config.maxTokens`}
|
||||
children={(field) => {
|
||||
const isInvalid =
|
||||
!!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel htmlFor={field.name} className="text-xs">
|
||||
Max Output Tokens
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id={field.name}
|
||||
name={field.name}
|
||||
type="number"
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) =>
|
||||
field.handleChange(parseInt(e.target.value) || 0)
|
||||
}
|
||||
aria-invalid={isInvalid}
|
||||
disabled={isBuiltin}
|
||||
/>
|
||||
{isInvalid && (
|
||||
<FieldError errors={mapErrors(field.state.meta.errors)} />
|
||||
)}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<form.Field
|
||||
name={`models[${index}].config.cost.input`}
|
||||
children={(field) => {
|
||||
const isInvalid =
|
||||
!!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel
|
||||
htmlFor={field.name}
|
||||
className="text-xs flex items-center gap-1"
|
||||
>
|
||||
<DollarSign className="w-3 h-3" /> Input Cost (1M)
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id={field.name}
|
||||
name={field.name}
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) =>
|
||||
field.handleChange(parseFloat(e.target.value) || 0)
|
||||
}
|
||||
aria-invalid={isInvalid}
|
||||
disabled={isBuiltin}
|
||||
/>
|
||||
{isInvalid && (
|
||||
<FieldError errors={mapErrors(field.state.meta.errors)} />
|
||||
)}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<form.Field
|
||||
name={`models[${index}].config.cost.output`}
|
||||
children={(field) => {
|
||||
const isInvalid =
|
||||
!!field.state.meta.errors.length && field.state.meta.isTouched
|
||||
return (
|
||||
<Field data-invalid={isInvalid}>
|
||||
<FieldLabel
|
||||
htmlFor={field.name}
|
||||
className="text-xs flex items-center gap-1"
|
||||
>
|
||||
<DollarSign className="w-3 h-3" /> Output Cost (1M)
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id={field.name}
|
||||
name={field.name}
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={field.state.value}
|
||||
onBlur={field.handleBlur}
|
||||
onChange={(e) =>
|
||||
field.handleChange(parseFloat(e.target.value) || 0)
|
||||
}
|
||||
aria-invalid={isInvalid}
|
||||
disabled={isBuiltin}
|
||||
/>
|
||||
{isInvalid && (
|
||||
<FieldError errors={mapErrors(field.state.meta.errors)} />
|
||||
)}
|
||||
</Field>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!isBuiltin && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="absolute -top-2 -right-2 h-8 w-8 rounded-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-400 hover:text-red-600 transition-colors shadow-sm"
|
||||
onClick={() => modelsField.removeValue(index)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="p-6 pt-4 border-t dark:border-slate-800 gap-2">
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<form.Subscribe
|
||||
selector={(state) => [state.canSubmit, state.isSubmitting]}
|
||||
children={([canSubmit, isSubmitting]) => (
|
||||
<Button
|
||||
type="submit"
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white min-w-[120px]"
|
||||
disabled={!canSubmit || isSubmitting || isLoading}
|
||||
>
|
||||
{isSubmitting || isLoading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
'Save Configuration'
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This action cannot be undone. This will permanently delete the provider and all
|
||||
associated model configurations.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-red-600 hover:bg-red-700 text-white"
|
||||
onClick={() => {
|
||||
onDelete?.()
|
||||
setIsDeleteDialogOpen(false)
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,637 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Code, Github, Loader2, MoreVertical, Plus, Puzzle, Trash2, Upload, X } from 'lucide-react'
|
||||
import React, { useState, useRef } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
// @ts-ignore - Import browser distribution to avoid Node.js built-ins in the bundle
|
||||
import JSZip from 'jszip/dist/jszip.min.js'
|
||||
import { SkillInfo } from '@/dtos/skill'
|
||||
|
||||
interface SkillsConfigCardProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export const SkillsConfigCard: React.FC<SkillsConfigCardProps> = ({ teamId }) => {
|
||||
const queryClient = useQueryClient()
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
|
||||
const [isConfigDialogOpen, setIsConfigDialogOpen] = useState(false)
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const [selectedSkill, setSelectedSkill] = useState<SkillInfo | null>(null)
|
||||
|
||||
// Fetch Skills
|
||||
const { data, isLoading } = 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()
|
||||
},
|
||||
})
|
||||
|
||||
// Delete Skill
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const res = await client.api.teams[':teamId'].skills[':id'].$delete({
|
||||
param: { teamId, id },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to delete skill')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'skills'] })
|
||||
setIsDeleteDialogOpen(false)
|
||||
},
|
||||
})
|
||||
|
||||
const skills = data?.skills || []
|
||||
|
||||
return (
|
||||
<Card className="border-slate-200 dark:border-slate-800">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-7">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 rounded-lg">
|
||||
<Puzzle className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-xl font-bold">Skills Management</CardTitle>
|
||||
<CardDescription>
|
||||
Extend your chatbot's capabilities with custom skills.
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={() => setIsAddDialogOpen(true)} className="gap-2">
|
||||
<Plus className="w-4 h-4" /> Add Skill
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center py-10">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
|
||||
</div>
|
||||
) : skills.length === 0 ? (
|
||||
<div className="text-center py-12 border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-xl">
|
||||
<div className="mx-auto w-12 h-12 bg-slate-50 dark:bg-slate-900 rounded-full flex items-center justify-center mb-4 text-slate-400">
|
||||
<Puzzle className="w-6 h-6" />
|
||||
</div>
|
||||
<h3 className="text-lg font-medium text-slate-900 dark:text-white">
|
||||
No skills installed
|
||||
</h3>
|
||||
<p className="text-slate-500 dark:text-slate-400 mt-1 max-w-xs mx-auto">
|
||||
Add a skill via GitHub URL or upload a ZIP file to get started.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{skills.map((skill) => (
|
||||
<SkillItem
|
||||
key={skill.id}
|
||||
skill={skill}
|
||||
onDelete={() => {
|
||||
setSelectedSkill(skill)
|
||||
setIsDeleteDialogOpen(true)
|
||||
}}
|
||||
onConfigure={() => {
|
||||
setSelectedSkill(skill)
|
||||
setIsConfigDialogOpen(true)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<AddSkillDialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen} teamId={teamId} />
|
||||
|
||||
{selectedSkill && (
|
||||
<ConfigSkillDialog
|
||||
open={isConfigDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsConfigDialogOpen(open)
|
||||
if (!open) {
|
||||
// Ensure body pointer-events is restored if something stuck it
|
||||
setTimeout(() => {
|
||||
document.body.style.pointerEvents = 'auto'
|
||||
}, 100)
|
||||
}
|
||||
}}
|
||||
teamId={teamId}
|
||||
skill={selectedSkill}
|
||||
/>
|
||||
)}
|
||||
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This action cannot be undone. This will permanently delete the skill "
|
||||
{selectedSkill?.name}" and all its configurations.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-red-600 hover:bg-red-700 text-white"
|
||||
onClick={() => {
|
||||
if (selectedSkill) {
|
||||
deleteMutation.mutate(selectedSkill.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{deleteMutation.isPending ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin mr-2" />
|
||||
) : (
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
const SkillItem = ({
|
||||
skill,
|
||||
onDelete,
|
||||
onConfigure,
|
||||
}: {
|
||||
skill: SkillInfo
|
||||
onDelete: () => void
|
||||
onConfigure: () => void
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
className="p-4 bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 flex flex-col justify-between hover:shadow-md transition-all group cursor-pointer"
|
||||
onClick={onConfigure}
|
||||
>
|
||||
<div>
|
||||
<div className="flex items-start justify-between mb-2">
|
||||
<h4 className="font-bold text-slate-900 dark:text-white flex items-center gap-2">
|
||||
{skill.name}
|
||||
</h4>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-32">
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDelete()
|
||||
}}
|
||||
className="text-red-500 focus:text-red-500 gap-2 cursor-pointer"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" /> Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400 line-clamp-2">
|
||||
{skill.description || 'No description provided.'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-between text-[10px] text-slate-400 dark:text-slate-500 uppercase tracking-wider font-semibold">
|
||||
<span>Updated {new Date(skill.updatedAt).toLocaleDateString()}</span>
|
||||
<div className="px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400">
|
||||
Installed
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const AddSkillDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
teamId,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
teamId: string
|
||||
}) => {
|
||||
const queryClient = useQueryClient()
|
||||
const [githubUrl, setGithubUrl] = useState('')
|
||||
const [isProcessing, setIsProcessing] = useState(false)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Need a project ID for the attachment upload
|
||||
const { data: projectsData } = useQuery({
|
||||
queryKey: ['teams', teamId, 'projects'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects.$get({
|
||||
param: { teamId },
|
||||
query: { first: '1' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch projects')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: open,
|
||||
})
|
||||
|
||||
const installSkill = async (payload: {
|
||||
assetId?: string
|
||||
githubUrl?: string
|
||||
override?: boolean
|
||||
}) => {
|
||||
setIsProcessing(true)
|
||||
try {
|
||||
const res = await client.api.teams[':teamId'].skills.$post({
|
||||
param: { teamId },
|
||||
json: payload,
|
||||
})
|
||||
|
||||
if (res.status === 409) {
|
||||
const data = (await res.json()) as { error: string }
|
||||
if (window.confirm(`${data.error}\n\nDo you want to override the existing skill?`)) {
|
||||
await installSkill({ ...payload, override: true })
|
||||
return
|
||||
}
|
||||
} else if (!res.ok) {
|
||||
const errorData = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
throw new Error(errorData.error || 'Failed to install skill')
|
||||
} else {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'skills'] })
|
||||
onOpenChange(false)
|
||||
setGithubUrl('')
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error) {
|
||||
alert(err.message)
|
||||
} else {
|
||||
alert('An unknown error occurred')
|
||||
}
|
||||
} finally {
|
||||
setIsProcessing(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileUpload = async (files: FileList | null) => {
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
const projectId = projectsData?.data?.[0]?.id
|
||||
if (!projectId) {
|
||||
alert('You need at least one project in your team to upload skills.')
|
||||
return
|
||||
}
|
||||
|
||||
setIsProcessing(true)
|
||||
|
||||
try {
|
||||
let fileToUpload: File | Blob
|
||||
let fileName: string
|
||||
let contentType = 'application/zip'
|
||||
|
||||
// Check if it's a ZIP file or a collection of files (folder)
|
||||
const isZip = files.length === 1 && files[0].name.toLowerCase().endsWith('.zip')
|
||||
|
||||
if (isZip) {
|
||||
fileToUpload = files[0]
|
||||
fileName = files[0].name
|
||||
contentType = files[0].type || 'application/zip'
|
||||
} else {
|
||||
const zip = new JSZip()
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const f = files[i]
|
||||
// Use relative path for folder structure if available
|
||||
const path = f.webkitRelativePath || f.name
|
||||
zip.file(path, f)
|
||||
}
|
||||
fileToUpload = await zip.generateAsync({ type: 'blob' })
|
||||
fileName = 'skill_package.zip'
|
||||
}
|
||||
|
||||
// 1. Get Presigned URL and Asset ID
|
||||
const attachRes = await client.api.projects[':projectId'].attachments.$post({
|
||||
param: { projectId },
|
||||
json: {
|
||||
fileName: fileName,
|
||||
size: fileToUpload.size,
|
||||
contentType: contentType,
|
||||
},
|
||||
})
|
||||
if (!attachRes.ok) throw new Error('Failed to get upload URL')
|
||||
const { id: assetId, uploadUrl } = (await attachRes.json()) as {
|
||||
id: string
|
||||
uploadUrl: string
|
||||
}
|
||||
|
||||
// 2. Upload to S3
|
||||
const uploadRes = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body: fileToUpload,
|
||||
headers: { 'Content-Type': contentType },
|
||||
})
|
||||
if (!uploadRes.ok) throw new Error('Failed to upload file to storage')
|
||||
|
||||
// 3. Install Skill
|
||||
await installSkill({ assetId })
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error) {
|
||||
alert(err.message)
|
||||
} else {
|
||||
alert('An unknown error occurred')
|
||||
}
|
||||
} finally {
|
||||
setIsProcessing(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[450px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add New Skill</DialogTitle>
|
||||
<DialogDescription>
|
||||
Import a skill from a local ZIP/folder or a GitHub repository.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 pt-4">
|
||||
{/* File/Folder Upload Section */}
|
||||
<div className="space-y-3">
|
||||
<Label>Package Upload</Label>
|
||||
<div
|
||||
onClick={() => !isProcessing && fileInputRef.current?.click()}
|
||||
className={cn(
|
||||
'group relative h-32 border-2 border-dashed rounded-xl flex flex-col items-center justify-center transition-all cursor-pointer',
|
||||
isProcessing
|
||||
? 'opacity-50 cursor-not-allowed bg-slate-50 dark:bg-slate-900 border-slate-200 dark:border-slate-800'
|
||||
: 'hover:bg-blue-50/50 dark:hover:bg-blue-900/10 hover:border-blue-500/50 border-slate-200 dark:border-slate-800',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
accept=".zip"
|
||||
// @ts-ignore
|
||||
webkitdirectory=""
|
||||
directory=""
|
||||
multiple
|
||||
onChange={(e) => handleFileUpload(e.target.files)}
|
||||
/>
|
||||
<div className="p-3 bg-slate-100 dark:bg-slate-800 rounded-full group-hover:bg-blue-100 dark:group-hover:bg-blue-900/30 transition-colors">
|
||||
<Upload className="w-6 h-6 text-slate-400 group-hover:text-blue-500" />
|
||||
</div>
|
||||
<div className="mt-3 text-center">
|
||||
<p className="text-sm font-medium text-slate-700 dark:text-slate-300">
|
||||
Select ZIP file or folder
|
||||
</p>
|
||||
<p className="text-[10px] text-slate-500 dark:text-slate-400 mt-1 uppercase tracking-wider font-semibold">
|
||||
Packages must contain a SKILL.md
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{isProcessing && !githubUrl && (
|
||||
<div className="flex items-center gap-2 text-sm text-blue-600 dark:text-blue-400 justify-center bg-blue-50 dark:bg-blue-900/10 py-2 rounded-lg animate-pulse">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Processing package...
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t border-slate-200 dark:border-slate-800" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-white dark:bg-slate-950 px-2 text-slate-500 font-bold">OR</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* GitHub URL Section */}
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="githubUrl">GitHub Repository URL</Label>
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Github className="absolute left-3 top-2.5 w-4 h-4 text-slate-400" />
|
||||
<Input
|
||||
id="githubUrl"
|
||||
placeholder="https://github.com/owner/repo"
|
||||
value={githubUrl}
|
||||
onChange={(e) => setGithubUrl(e.target.value)}
|
||||
disabled={isProcessing}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => installSkill({ githubUrl })}
|
||||
disabled={!githubUrl || isProcessing}
|
||||
className="px-6"
|
||||
>
|
||||
{isProcessing && githubUrl ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
'Install'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-[10px] text-slate-500 dark:text-slate-400 italic">
|
||||
Example: https://github.com/google/gemini-cli
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
const ConfigSkillDialog = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
teamId,
|
||||
skill,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
teamId: string
|
||||
skill: SkillInfo
|
||||
}) => {
|
||||
const queryClient = useQueryClient()
|
||||
const [config, setConfig] = useState({
|
||||
...(skill.config || {}),
|
||||
environmentVariables: skill.config?.environmentVariables || [],
|
||||
})
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
|
||||
const handleEnvVarValueChange = (index: number, value: string) => {
|
||||
const newVars = [...config.environmentVariables]
|
||||
newVars[index] = { ...newVars[index], default: value }
|
||||
setConfig({ ...config, environmentVariables: newVars })
|
||||
}
|
||||
|
||||
const handleEnvVarNameChange = (index: number, name: string) => {
|
||||
const newVars = [...config.environmentVariables]
|
||||
newVars[index] = { ...newVars[index], name }
|
||||
setConfig({ ...config, environmentVariables: newVars })
|
||||
}
|
||||
|
||||
const addEnvVar = () => {
|
||||
setConfig({
|
||||
...config,
|
||||
environmentVariables: [...config.environmentVariables, { name: '', default: '' }],
|
||||
})
|
||||
}
|
||||
|
||||
const removeEnvVar = (index: number) => {
|
||||
const newVars = [...config.environmentVariables]
|
||||
newVars.splice(index, 1)
|
||||
setConfig({ ...config, environmentVariables: newVars })
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
// Basic validation: filter out empty names
|
||||
const filteredVars = config.environmentVariables.filter((v) => v.name.trim() !== '')
|
||||
const finalConfig = { ...config, environmentVariables: filteredVars }
|
||||
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const res = await client.api.teams[':teamId'].skills[':id'].config.$patch({
|
||||
param: { teamId, id: skill.id },
|
||||
json: { config: finalConfig },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const errorData = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
throw new Error(errorData.error || 'Failed to update config')
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'skills'] })
|
||||
onOpenChange(false)
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error) {
|
||||
alert(err.message)
|
||||
} else {
|
||||
alert('An unknown error occurred')
|
||||
}
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const envVars = config?.environmentVariables || []
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Code className="w-5 h-5 text-blue-500" />
|
||||
Configure Skill: {skill.name}
|
||||
</DialogTitle>
|
||||
</div>
|
||||
<DialogDescription>
|
||||
Manage environment variables for this skill instance.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-4 space-y-4 max-h-[60vh] overflow-y-auto pr-2 custom-scrollbar">
|
||||
{envVars.length === 0 ? (
|
||||
<div className="text-center py-10 bg-slate-50 dark:bg-slate-900 rounded-xl border border-dashed border-slate-200 dark:border-slate-800">
|
||||
<p className="text-slate-500 dark:text-slate-400 text-sm italic">
|
||||
No environment variables found. Click "Add Variable" to create one.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
envVars.map((env: { name: string; default?: string | undefined }, index: number) => (
|
||||
<div
|
||||
key={index}
|
||||
className="p-4 bg-slate-100/50 dark:bg-slate-800/50 rounded-xl border border-slate-200 dark:border-slate-700 space-y-3 relative group"
|
||||
>
|
||||
<button
|
||||
onClick={() => removeEnvVar(index)}
|
||||
className="absolute top-2 right-2 p-1 text-slate-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-md transition-colors opacity-0 group-hover:opacity-100"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider font-bold text-slate-400">
|
||||
Variable Name
|
||||
</Label>
|
||||
<Input
|
||||
value={env.name}
|
||||
onChange={(e) => handleEnvVarNameChange(index, e.target.value)}
|
||||
placeholder="e.app. API_KEY"
|
||||
className="h-8 bg-white dark:bg-slate-950 border-slate-200 dark:border-slate-800 text-sm font-mono"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider font-bold text-slate-400">
|
||||
Default Value
|
||||
</Label>
|
||||
<Input
|
||||
value={env.default || ''}
|
||||
onChange={(e) => handleEnvVarValueChange(index, e.target.value)}
|
||||
placeholder="Optional default value..."
|
||||
className="h-8 bg-white dark:bg-slate-950 border-slate-200 dark:border-slate-800 text-sm"
|
||||
/>
|
||||
<p className="text-[10px] text-slate-500 italic">
|
||||
If left empty, the value will be read from the host machine's environment.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex items-center justify-between sm:justify-between w-full pt-2 border-t border-slate-100 dark:border-slate-800">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={addEnvVar}
|
||||
className="h-8 gap-1.5 text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" /> Add Variable
|
||||
</Button>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="ghost" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={isSaving}
|
||||
className="px-8 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
>
|
||||
{isSaving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
|
||||
Save Changes
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { AiProvider } from './types'
|
||||
|
||||
export const PROVIDERS = [
|
||||
{ value: AiProvider.GEMINI, label: 'Google Gemini' },
|
||||
{ value: AiProvider.openAi, label: 'OpenAi' },
|
||||
{ value: AiProvider.ANTHROPIC, label: 'Anthropic' },
|
||||
]
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { AiProviderSettings } from '@/dtos/ai'
|
||||
|
||||
export const AiProvider = {
|
||||
GEMINI: 'google',
|
||||
openAi: 'openai',
|
||||
ANTHROPIC: 'anthropic',
|
||||
ELEVEN: 'elevenlabs',
|
||||
} as const
|
||||
export type AiProvider = (typeof AiProvider)[keyof typeof AiProvider]
|
||||
|
||||
export const GeminiModel = {
|
||||
FLASH: 'gemini-3-flash-preview',
|
||||
PRO: 'gemini-3-pro-preview',
|
||||
FLASH_LITE: 'gemini-flash-lite-latest',
|
||||
} as const
|
||||
export type GeminiModel = (typeof GeminiModel)[keyof typeof GeminiModel]
|
||||
|
||||
export const FileType = {
|
||||
IMAGE: 'image',
|
||||
VIDEO: 'video',
|
||||
AUDIO: 'audio',
|
||||
TEXT: 'text',
|
||||
} as const
|
||||
export type FileType = (typeof FileType)[keyof typeof FileType]
|
||||
|
||||
export const ThinkingLevel = {
|
||||
DISABLED: 'disabled',
|
||||
LOW: 'low',
|
||||
MEDIUM: 'medium',
|
||||
HIGH: 'high',
|
||||
} as const
|
||||
export type ThinkingLevel = (typeof ThinkingLevel)[keyof typeof ThinkingLevel]
|
||||
|
||||
import type { AgentInfo } from '@/dtos/agent'
|
||||
|
||||
export type ProviderSettings = AiProviderSettings
|
||||
export type Agent = AgentInfo
|
||||
Reference in New Issue
Block a user