import { useState } from 'react' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { client } from '@/ui/api/client' import { ScrollArea } from '@/ui/components/ui/scroll-area' import { Card, CardContent } from '@/ui/components/ui/card' import { Input } from '@/ui/components/ui/input' import { Button } from '@/ui/components/ui/button' import { Badge } from '@/ui/components/ui/badge' import { Label } from '@/ui/components/ui/label' import { Switch } from '@/ui/components/ui/switch' import { Textarea } from '@/ui/components/ui/textarea' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/ui/components/ui/dialog' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/ui/components/ui/alert-dialog' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { Check, Copy, Edit2, KeyRound, Loader2, MoreVertical, Plus, RefreshCw, Star, Terminal, Trash2, } from 'lucide-react' import { toast } from 'sonner' import { m } from '@/ui/paraglide/messages.js' import type { RunnerInfo } from '@shumai/dtos' export function RunnerSettings({ teamId }: { teamId: string }) { const queryClient = useQueryClient() // Create Dialog state const [isCreateOpen, setIsCreateOpen] = useState(false) const [newName, setNewName] = useState('') const [newDescription, setNewDescription] = useState('') const [newIsDefault, setNewIsDefault] = useState(false) // Edit Dialog state const [editingRunner, setEditingRunner] = useState(null) const [editName, setEditName] = useState('') const [editDescription, setEditDescription] = useState('') // Rotate & Delete Confirm Dialog state const [runnerToRotate, setRunnerToRotate] = useState(null) const [runnerToDelete, setRunnerToDelete] = useState(null) // One-time Key Reveal Dialog state const [revealedKeyData, setRevealedKeyData] = useState<{ name: string key: string } | null>(null) const [copiedField, setCopiedField] = useState(null) const { data, isLoading } = useQuery({ queryKey: ['teams', teamId, 'runners'], queryFn: async () => { const res = await client.api.teams[':teamId'].runners.$get({ param: { teamId }, }) if (!res.ok) throw new Error(m.failed_to_load_runners()) return await res.json() }, refetchInterval: 5000, }) const runners = data ?? [] const createRunnerMutation = useMutation({ mutationFn: async (params: { name: string; description?: string; isDefault?: boolean }) => { const res = await client.api.teams[':teamId'].runners.$post({ param: { teamId }, json: params, }) if (!res.ok) throw new Error(m.failed_to_create_runner()) return await res.json() }, onSuccess: (created) => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'runners'] }) setIsCreateOpen(false) setNewName('') setNewDescription('') setNewIsDefault(false) setRevealedKeyData({ name: created.runner.name, key: created.key }) toast.success(m.runner_created_successfully()) }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_create_runner()) }, }) const updateRunnerMutation = useMutation({ mutationFn: async (params: { runnerId: string name?: string description?: string | null isDefault?: boolean }) => { const res = await client.api.teams[':teamId'].runners[':runnerId'].$patch({ param: { teamId, runnerId: params.runnerId }, json: { name: params.name, description: params.description, isDefault: params.isDefault, }, }) if (!res.ok) throw new Error(m.failed_to_update_runner()) return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'runners'] }) setEditingRunner(null) toast.success(m.runner_updated_successfully()) }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_update_runner()) }, }) const rotateKeyMutation = useMutation({ mutationFn: async (runnerId: string) => { const res = await client.api.teams[':teamId'].runners[':runnerId']['rotate-key'].$post({ param: { teamId, runnerId }, }) if (!res.ok) throw new Error(m.failed_to_rotate_runner_key()) return await res.json() }, onSuccess: (rotated) => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'runners'] }) setRunnerToRotate(null) setRevealedKeyData({ name: rotated.runner.name, key: rotated.key }) toast.success(m.runner_key_rotated_successfully()) }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_rotate_runner_key()) }, }) const deleteRunnerMutation = useMutation({ mutationFn: async (runnerId: string) => { const res = await client.api.teams[':teamId'].runners[':runnerId'].$delete({ param: { teamId, runnerId }, }) if (!res.ok) throw new Error(m.failed_to_delete_runner()) return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'runners'] }) setRunnerToDelete(null) toast.success(m.runner_deleted_successfully()) }, onError: (err) => { toast.error(err instanceof Error ? err.message : m.failed_to_delete_runner()) }, }) const handleCopy = async (text: string, field: string) => { try { await navigator.clipboard.writeText(text) setCopiedField(field) toast.success(m.runner_copied_to_clipboard()) setTimeout(() => { setCopiedField((prev) => (prev === field ? null : prev)) }, 2000) } catch { // Ignore clipboard failure } } const serverOrigin = typeof window !== 'undefined' ? window.location.origin : '' if (isLoading) { return (
) } return ( <>
{runners.length > 0 ? `${runners.length} ${m.runners()}` : ''}
{runners.length === 0 ? (

{m.runner_empty_title()}

{m.runner_empty_description()}

) : (
{runners.map((runner) => { const isOnline = runner.status === 'connected' return (
{runner.name} {isOnline ? m.runner_status_connected() : m.runner_status_disconnected()} {runner.isDefault && ( {m.runner_default_badge()} )}
{runner.description && (

{runner.description}

)}
{m.runner_key_prefix_label()}: {runner.keyPrefix}... {runner.lastConnectedAt ? m.runner_last_seen_label({ time: new Date(runner.lastConnectedAt).toLocaleString(), }) : m.runner_never_connected()}
{!runner.isDefault && ( updateRunnerMutation.mutate({ runnerId: runner.id, isDefault: true, }) } className="gap-2 cursor-pointer" > {m.runner_set_default_action()} )} { setEditingRunner(runner) setEditName(runner.name) setEditDescription(runner.description || '') }} className="gap-2 cursor-pointer" > {m.runner_edit_action()} setRunnerToRotate(runner)} className="gap-2 cursor-pointer" > {m.runner_rotate_key_action()} setRunnerToDelete(runner)} className="text-destructive focus:text-destructive gap-2 cursor-pointer" > {m.delete()}
) })}
)}
{/* Create Runner Dialog */} {m.create_runner()} {m.create_runner_description()}
{ e.preventDefault() if (!newName.trim()) return createRunnerMutation.mutate({ name: newName.trim(), description: newDescription.trim() || undefined, isDefault: newIsDefault || runners.length === 0, }) }} className="space-y-4" >
setNewName(e.target.value)} placeholder={m.runner_name_placeholder()} required />