import { client } from '@/ui/api/client' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Code, 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 { ScrollArea } from '@/ui/components/ui/scroll-area' 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' import { SkillInfo } from '@shumai/dtos' import { m } from '@/ui/paraglide/messages.js' import { usePermissions } from '@/ui/hooks/use-permissions' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/ui/components/ui/select' const Github = (props: React.SVGProps) => ( ) interface SkillsConfigCardProps { teamId: string } export const SkillsConfigCard: React.FC = ({ teamId }) => { const queryClient = useQueryClient() const { canAdmin } = usePermissions() const [isAddDialogOpen, setIsAddDialogOpen] = useState(false) const [isConfigDialogOpen, setIsConfigDialogOpen] = useState(false) const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false) const [selectedSkill, setSelectedSkill] = useState(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(m.failed_load_settings()) return await res.json() }, }) // Delete Skill const deleteMutation = useMutation({ mutationFn: async (id: string) => { const res = await client.api.skills[':id'].$delete({ param: { id }, }) if (!res.ok) throw new Error(m.failed_to_delete()) }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'skills'] }) setIsDeleteDialogOpen(false) }, }) // Update Skill Permission const updatePermissionMutation = useMutation({ mutationFn: async ({ id, permission, }: { id: string permission: 'owner' | 'editor' | 'reviewer' }) => { const res = await client.api.skills[':id'].permission.$patch({ param: { id }, json: { permission }, }) if (!res.ok) throw new Error(m.failed_to_update_permission()) }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'skills'] }) }, onError: (err: Error) => { alert(err.message || m.failed_to_update_permission()) }, }) const skills = data?.skills || [] return (
{m.skills_management()} {m.skills_management_description()}
{isLoading ? (
) : skills.length === 0 ? (

{m.no_skills_installed()}

{m.add_skill_to_get_started()}

) : (
{skills.map((skill) => ( { setSelectedSkill(skill) setIsDeleteDialogOpen(true) }} onConfigure={() => { setSelectedSkill(skill) setIsConfigDialogOpen(true) }} onPermissionChange={(permission) => updatePermissionMutation.mutate({ id: skill.id, permission }) } /> ))}
)}
{selectedSkill && ( { 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} /> )} {m.are_you_absolutely_sure()} {m.delete_skill_confirmation({ name: selectedSkill?.name ?? '' })} {m.cancel()} { if (selectedSkill) { deleteMutation.mutate(selectedSkill.id) } }} > {deleteMutation.isPending ? ( ) : ( )} {m.delete()}
) } const SkillItem = ({ skill, canAdmin, onDelete, onConfigure, onPermissionChange, }: { skill: SkillInfo canAdmin: boolean onDelete: () => void onConfigure: () => void onPermissionChange: (permission: 'owner' | 'editor' | 'reviewer') => void }) => { return (

{skill.name}

e.stopPropagation()}> { e.stopPropagation() onDelete() }} className="text-destructive focus:text-destructive gap-2 cursor-pointer" > {m.delete()}

{skill.description || m.no_description_provided()}

{m.updated_date()} {new Date(skill.updatedAt).toLocaleDateString()}
e.stopPropagation()}>
) } 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(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\n${m.override_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 || m.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(m.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(m.need_project_to_upload_skills()) return } const fileToUpload = files[0] if (!fileToUpload.name.toLowerCase().endsWith('.zip')) { alert(m.only_zip_files_supported()) return } setIsProcessing(true) try { const fileName = fileToUpload.name const contentType = fileToUpload.type || 'application/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(m.an_unknown_error_occurred()) } } finally { setIsProcessing(false) } } return ( {m.add_new_skill()} {m.import_skill_description()}
{/* File Upload Section */}
!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-muted/50 border-border' : 'hover:bg-primary/5 hover:border-primary/50 border-border', )} > handleFileUpload(e.target.files)} />

{m.select_zip_file()}

{m.packages_must_contain_skill_md()}

{isProcessing && !githubUrl && (
{m.processing_package()}
)}
{m.or()}
{/* GitHub URL Section */}
setGithubUrl(e.target.value)} disabled={isProcessing} className="pl-9" />

{m.github_url_example()}

) } 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.skills[':id'].config.$patch({ param: { 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(m.an_unknown_error_occurred()) } } finally { setIsSaving(false) } } const envVars = config?.environmentVariables || [] return (
{m.configure_skill({ name: skill.name })}
{m.manage_env_vars_description()}
{envVars.length === 0 ? (

{m.no_env_vars_found()}

) : ( envVars.map((env: { name: string; default?: string | undefined }, index: number) => (
handleEnvVarNameChange(index, e.target.value)} placeholder="e.g. API_KEY" className="h-8 bg-background border-border text-sm font-mono" />
handleEnvVarValueChange(index, e.target.value)} placeholder={m.optional_default_value_placeholder()} className="h-8 bg-background border-border text-sm" />

{m.env_var_empty_note()}

)) )}
) }