All files / web/src/components/ai-providers ai-providers-list.tsx

82% Statements 246/300
92.85% Branches 26/28
35.71% Functions 5/14
82% Lines 246/300

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385      1x 1x 1x             1x           1x 1x 1x 1x               1x 1x 1x 1x 1x                     1x 1x             1x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x   41x 41x 41x 41x 41x   41x 120x 78x 78x 78x 67x   78x 42x 41x   41x                                                                         41x         41x                 41x 46x           46x 46x 46x 46x   41x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x   41x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x   40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x   40x   40x 40x 40x 40x 40x 1x 39x 41x 41x 41x 41x   41x 41x 41x 41x 41x 41x 41x 41x 41x     41x 11x 11x 11x   11x 11x 11x 10x 1x 11x 11x 1x 1x   1x   1x   11x   29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 61x 61x 61x 61x 3x 58x 61x 61x 1x 60x 61x 61x   61x 61x 61x 61x 61x 61x 61x   61x 61x 61x 61x 61x 46x 46x 46x 46x 46x 46x 46x 46x         46x     46x   46x 46x   15x   15x   61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x   61x 61x 61x 61x 61x 61x           61x   61x 61x 61x       61x 61x   61x   61x 61x 61x 61x 61x 29x 29x 29x   41x 41x 41x 41x   41x 41x 41x 41x 41x 41x 41x   41x  
'use client';
 
import type { AIProviderConfig } from '@shared/types/data/ai-provider';
import { Badge } from '@web/components/ui/badge';
import { Button } from '@web/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@web/components/ui/card';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@web/components/ui/dropdown-menu';
import { Input } from '@web/components/ui/input';
import { PageHeader } from '@web/components/ui/page-header';
import { Skeleton } from '@web/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@web/components/ui/table';
import { usePermissiveNavigate } from '@web/hooks/use-permissive-navigate';
import { useToast } from '@web/hooks/use-toast';
import { useAIProviders } from '@web/providers/ai-providers';
import { format } from 'date-fns';
import {
  CableIcon,
  CheckIcon,
  CopyIcon,
  KeyIcon,
  MoreHorizontalIcon,
  PlusIcon,
  SearchIcon,
  TrashIcon,
} from 'lucide-react';
import type { ReactElement } from 'react';
import { useState } from 'react';
import { DeleteAIProviderDialog } from './delete-ai-provider-dialog';
 
interface AIProvidersListViewProps {
  onProviderSelect?: (providerId: string) => void;
  selectedProviderId?: string | null;
}
 
export function AIProvidersListView({
  onProviderSelect,
  selectedProviderId,
}: AIProvidersListViewProps = {}): ReactElement {
  const navigate = usePermissiveNavigate();
  const { toast } = useToast();
  const {
    aiProviderConfigs: apiKeys,
    isLoading,
    deleteAPIKey,
    isDeleting,
  } = useAIProviders();
 
  const [searchQuery, setSearchQuery] = useState('');
  const [copiedKeys, setCopiedKeys] = useState<Set<string>>(new Set());
  const [providerToDelete, setProviderToDelete] =
    useState<AIProviderConfig | null>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
 
  const filteredAPIKeys = apiKeys.filter((apiKey) => {
    if (searchQuery) {
      const searchLower = searchQuery.toLowerCase();
      return (
        apiKey.name?.toLowerCase().includes(searchLower) ||
        apiKey.ai_provider?.toLowerCase().includes(searchLower)
      );
    }
    return true;
  });
 
  const copyToClipboard = async (apiKey: AIProviderConfig) => {
    try {
      if (!apiKey.api_key) {
        toast({
          title: 'No API key',
          description: 'This provider does not have an API key configured.',
          variant: 'destructive',
        });
        return;
      }
      await navigator.clipboard.writeText(apiKey.api_key);
      const newCopiedKeys = new Set(copiedKeys);
      newCopiedKeys.add(apiKey.id);
      setCopiedKeys(newCopiedKeys);
 
      toast({
        title: 'Copied to clipboard',
        description: `API key "${apiKey.name}" copied to clipboard.`,
      });
 
      // Remove the copied state after 2 seconds
      setTimeout(() => {
        setCopiedKeys((prev) => {
          const newSet = new Set(prev);
          newSet.delete(apiKey.id);
          return newSet;
        });
      }, 2000);
    } catch (_error) {
      toast({
        title: 'Failed to copy',
        description: 'Could not copy API key to clipboard.',
        variant: 'destructive',
      });
    }
  };
 
  const handleDeleteClick = (apiKey: AIProviderConfig) => {
    setProviderToDelete(apiKey);
    setIsDeleteDialogOpen(true);
  };
 
  const handleDeleteConfirm = async () => {
    if (!providerToDelete) return;
    try {
      await deleteAPIKey(providerToDelete.id);
    } catch (_error) {
      // Error handling is done in the provider
    }
  };
 
  const maskAPIKey = (apiKey: string): string => {
    if (apiKey.length <= 8) {
      // If key is too short, just show dots (fixed length for security)
      return '•'.repeat(10);
    }
    // Always show first 4 characters, 10 dots, and last 4 characters
    // This hides the actual length of the API key for security
    const first4 = apiKey.slice(0, 4);
    const last4 = apiKey.slice(-4);
    return `${first4}${'•'.repeat(10)}${last4}`;
  };
 
  const getProviderColor = (provider: string): string => {
    const colors: Record<string, string> = {
      openai:
        'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',
      anthropic:
        'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-300',
      google: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300',
      default: 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300',
    };
    return colors[provider.toLowerCase()] || colors.default;
  };
 
  if (isLoading) {
    return (
      <>
        <PageHeader
          title="AI Providers & Models"
          description="Configure AI providers and manage available models"
          showBackButton={false}
          actions={
            <div className="flex gap-2">
              <Skeleton className="h-10 w-20" />
              <Skeleton className="h-10 w-32" />
            </div>
          }
        />
        <div className="px-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <KeyIcon className="h-5 w-5" />
                AI Providers
              </CardTitle>
              <CardDescription>
                Manage your AI providers and their configurations
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <Skeleton className="h-10 w-full" />
                <div className="space-y-2">
                  <Skeleton className="h-12 w-full" />
                  <Skeleton className="h-12 w-full" />
                  <Skeleton className="h-12 w-full" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </>
    );
  }
 
  return (
    <>
      <PageHeader
        title="AI Providers & Models"
        description="Configure AI providers and manage available models"
        showBackButton={false}
      />
      <div className="px-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 w-full p-0 m-0">
              <div className="flex items-center gap-2 w-full p-0 m-0">
                <CableIcon className="h-5 w-5" /> AI Providers (
                {filteredAPIKeys.length})
              </div>
              <div className="flex gap-2">
                <Button
                  onClick={() => navigate({ to: '/ai-providers/create' })}
                >
                  <PlusIcon className="h-4 w-4 mr-2" />
                  Add AI Provider
                </Button>
              </div>
            </CardTitle>
            <CardDescription className="p-0 m-0">
              {onProviderSelect
                ? 'Select a provider to view and manage its models below'
                : 'Manage your AI providers. API keys are encrypted and stored securely.'}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {/* Search */}
              <div className="relative">
                <SearchIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Search by provider or name..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10"
                />
              </div>
 
              {/* API Keys Table */}
              {filteredAPIKeys.length === 0 ? (
                <div className="text-center py-8">
                  <KeyIcon className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                  <h3 className="text-lg font-semibold mb-2">
                    No AI providers found
                  </h3>
                  <p className="text-muted-foreground mb-4">
                    {searchQuery
                      ? 'No AI providers match your search criteria.'
                      : 'Get started by adding your first AI provider.'}
                  </p>
                  {!searchQuery && (
                    <Button
                      onClick={() => navigate({ to: '/ai-providers/create' })}
                    >
                      <PlusIcon className="h-4 w-4 mr-2" />
                      Add Your First AI Provider
                    </Button>
                  )}
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Name</TableHead>
                      <TableHead>Provider</TableHead>
                      <TableHead>API Key</TableHead>
                      <TableHead>Created</TableHead>
                      <TableHead className="w-[100px]">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredAPIKeys.map((apiKey) => (
                      <TableRow
                        key={apiKey.id}
                        className={`${
                          onProviderSelect
                            ? 'cursor-pointer hover:bg-muted/50'
                            : ''
                        } ${
                          selectedProviderId === apiKey.id
                            ? 'bg-muted/30 border-l-4 border-l-primary'
                            : ''
                        }`}
                        onClick={() => onProviderSelect?.(apiKey.id)}
                      >
                        <TableCell className="font-medium">
                          {apiKey.name}
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant="secondary"
                            className={getProviderColor(apiKey.ai_provider)}
                          >
                            {apiKey.ai_provider}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          {apiKey.api_key ? (
                            <div className="flex items-center gap-2">
                              <code className="text-sm font-mono bg-muted px-2 py-1 rounded">
                                {maskAPIKey(apiKey.api_key)}
                              </code>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  copyToClipboard(apiKey);
                                }}
                              >
                                {copiedKeys.has(apiKey.id) ? (
                                  <CheckIcon className="h-4 w-4 text-green-600" />
                                ) : (
                                  <CopyIcon className="h-4 w-4" />
                                )}
                              </Button>
                            </div>
                          ) : (
                            <span className="text-sm text-muted-foreground italic">
                              No API key set
                            </span>
                          )}
                        </TableCell>
                        <TableCell className="text-muted-foreground">
                          {format(new Date(apiKey.created_at), 'MMM d, yyyy')}
                        </TableCell>
                        <TableCell>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={(e) => e.stopPropagation()}
                              >
                                <MoreHorizontalIcon className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem
                                onClick={() =>
                                  navigate({
                                    to: '/ai-providers/$id/edit',
                                    params: { id: apiKey.id },
                                  })
                                }
                              >
                                Edit
                              </DropdownMenuItem>
                              <DropdownMenuItem
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleDeleteClick(apiKey);
                                }}
                                disabled={isDeleting}
                                className="text-destructive"
                              >
                                <TrashIcon className="h-4 w-4 mr-2" />
                                Delete
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
 
      <DeleteAIProviderDialog
        provider={providerToDelete}
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        onConfirm={handleDeleteConfirm}
      />
    </>
  );
}