All files / web/src/components/ai-providers api-key-form.tsx

63.92% Statements 241/377
78.84% Branches 41/52
60% Functions 6/10
63.92% Lines 241/377

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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510    1x 1x                     1x 1x 1x             1x               1x                 1x 1x 1x         1x 1x 1x                 1x   1x 1x   1x   1x 1x 54x 54x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x                 1x 42x 42x 42x 42x 42x   42x 42x 42x     42x                                                                                           42x 42x 42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 42x   42x     42x 14x 14x 14x 14x 14x   14x 14x 14x 14x 14x 42x     42x 28x 28x 4x 28x     28x     28x 2x 2x 42x   42x                                                                                           42x 2x 2x   42x     42x 42x 42x   42x   42x 42x 42x 42x 42x 42x 36x 6x   42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 36x 6x 42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 42x 42x 42x   42x         42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 2268x 2268x 2268x 2268x         2268x 2268x 2268x   2268x   2268x 2268x 2268x 42x 42x 42x 42x 42x 42x 42x 42x   42x   42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x   42x   42x 42x 42x 42x 42x 42x   42x   42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x   42x     42x   42x 42x 42x 42x 42x   42x   42x 14x                                                                                                                                             42x   42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 6x 6x 6x 6x   36x 36x 36x 33x 3x 36x   42x 42x 42x 42x 42x 42x 42x 42x   42x  
'use client';
 
import { zodResolver } from '@hookform/resolvers/zod';
import {
  AIProvider,
  DEFAULT_SELF_HOSTED_URLS,
  PrettyAIProvider,
} from '@shared/types/constants';
import type {
  AIProviderConfig,
  AIProviderConfigCreateParams,
  AIProviderConfigUpdateParams,
} from '@shared/types/data/ai-provider';
import type { AIProviderSchemaResponse } from '@web/api/v1/super-agents/ai-providers';
import { getAIProviderSchemas } from '@web/api/v1/super-agents/ai-providers';
import { Button } from '@web/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@web/components/ui/card';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@web/components/ui/command';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@web/components/ui/form';
import { Input } from '@web/components/ui/input';
import { PageHeader } from '@web/components/ui/page-header';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@web/components/ui/popover';
import { usePermissiveNavigate } from '@web/hooks/use-permissive-navigate';
import { useAIProviders } from '@web/providers/ai-providers';
import {
  Check,
  ChevronsUpDown,
  EyeIcon,
  EyeOffIcon,
  KeyIcon,
  SaveIcon,
} from 'lucide-react';
import type { ReactElement } from 'react';
import { useEffect, useRef, useState } from 'react';
import type { FieldErrors } from 'react-hook-form';
import { useForm, useWatch } from 'react-hook-form';
import { z } from 'zod';
 
const MAX_NAME_LENGTH = 100;
 
const AI_PROVIDERS = Object.values(AIProvider)
  .map((provider) => ({
    value: provider,
    label: PrettyAIProvider[provider],
  }))
  .sort((a, b) => a.label.localeCompare(b.label));
 
const formSchema = z.object({
  ai_provider: z.string().min(1, 'Provider is required'),
  name: z
    .string()
    .min(1, 'Name is required')
    .max(MAX_NAME_LENGTH, `Name must be ${MAX_NAME_LENGTH} characters or less`),
  api_key: z.string().nullable().optional(),
  custom_fields: z.record(z.string(), z.unknown()).default({}),
});
 
type FormData = z.infer<typeof formSchema>;
 
interface APIKeyFormProps {
  apiKey?: AIProviderConfig;
  mode: 'create' | 'edit';
}
 
export function APIKeyForm({ apiKey, mode }: APIKeyFormProps): ReactElement {
  const navigate = usePermissiveNavigate();
  const { createAPIKey, updateAPIKey, isCreating, isUpdating } =
    useAIProviders();
  const [showAPIKey, setShowAPIKey] = useState(false);
  const [providerSchemas, setProviderSchemas] = useState<
    Record<string, AIProviderSchemaResponse>
  >({});
  const [schemasLoading, setSchemasLoading] = useState(true);
  const [providerComboboxOpen, setProviderComboboxOpen] = useState(false);
 
  // Custom resolver that validates API key based on provider requirements
  const customResolver = async (
    data: FormData,
    context: unknown,
    // biome-ignore lint/suspicious/noExplicitAny: resolver options type compatibility
    options: any,
  ) => {
    // First run base schema validation
    const baseResult = await zodResolver(formSchema)(data, context, options);
 
    // Additional API key validation based on provider
    const selectedSchema = providerSchemas[data.ai_provider];
    if (selectedSchema?.isAPIKeyRequired) {
      const isAPIKeyEmpty = !data.api_key || data.api_key.trim() === '';
 
      // In create mode, API key is required
      if (mode === 'create' && isAPIKeyEmpty) {
        return {
          values: {},
          errors: {
            ...baseResult.errors,
            api_key: {
              type: 'manual',
              message: 'API key is required for this provider',
            },
          } as FieldErrors<FormData>,
        };
      }
 
      // In edit mode, only required if no existing key
      if (mode === 'edit' && isAPIKeyEmpty && !apiKey?.api_key) {
        return {
          values: {},
          errors: {
            ...baseResult.errors,
            api_key: {
              type: 'manual',
              message: 'API key is required for this provider',
            },
          } as FieldErrors<FormData>,
        };
      }
    }
 
    return baseResult;
  };
 
  const form = useForm({
    resolver: customResolver,
    defaultValues: {
      ai_provider: apiKey?.ai_provider || '',
      name: apiKey?.name || '',
      api_key: apiKey?.api_key || '',
      custom_fields: apiKey?.custom_fields || {},
    },
  });
 
  const selectedProvider = useWatch({
    control: form.control,
    name: 'ai_provider',
  });
 
  const prevProviderRef = useRef<string>(selectedProvider);
 
  // Fetch provider schemas on mount
  useEffect(() => {
    const fetchSchemas = async () => {
      try {
        const schemas = await getAIProviderSchemas();
        setProviderSchemas(schemas);
      } catch (error) {
        console.error('Failed to fetch provider schemas:', error);
      } finally {
        setSchemasLoading(false);
      }
    };
    fetchSchemas();
  }, []);
 
  // Auto-clear custom_fields when switching providers and update validation
  useEffect(() => {
    if (
      prevProviderRef.current &&
      prevProviderRef.current !== selectedProvider
    ) {
      form.setValue('custom_fields', {});
    }
    prevProviderRef.current = selectedProvider;
 
    // Clear existing errors when provider changes
    if (selectedProvider && providerSchemas[selectedProvider]) {
      form.clearErrors();
    }
  }, [selectedProvider, form, providerSchemas]);
 
  const onSubmit = async (data: FormData) => {
    try {
      if (mode === 'create') {
        const createParams: AIProviderConfigCreateParams = {
          ai_provider: data.ai_provider,
          name: data.name,
          api_key: data.api_key,
          custom_fields: data.custom_fields || {},
        };
        const newProvider = await createAPIKey(createParams);
 
        // Reset form after successful creation to clear data
        form.reset();
 
        // Navigate to add models view for the new provider
        // The mutation's onSuccess already waits for cache invalidation
        navigate({
          to: '/ai-providers/$id/add-models',
          params: { id: newProvider.id },
        });
      } else if (apiKey) {
        const updateParams: AIProviderConfigUpdateParams = {
          ai_provider: data.ai_provider,
          name: data.name,
          ...(data.api_key !== apiKey.api_key && { api_key: data.api_key }),
        };
 
        // Only include custom_fields if they have changed
        if (
          JSON.stringify(data.custom_fields) !==
          JSON.stringify(apiKey.custom_fields)
        ) {
          updateParams.custom_fields = data.custom_fields || {};
        }
 
        await updateAPIKey(apiKey.id, updateParams);
        navigate({ to: '/ai-providers' });
      }
    } catch (error) {
      // Error handling is done in the provider, but log for debugging
      console.error('Error in form submission:', error);
      // Re-throw to prevent navigation on error
      throw error;
    }
  };
 
  const handleBack = () => {
    window.history.back();
  };
 
  const isSubmitting = isCreating || isUpdating;
 
  // Check if the selected provider has custom fields
  const selectedProviderSchema = providerSchemas[selectedProvider];
  const hasCustomFields = Boolean(
    selectedProviderSchema?.hasCustomFields &&
      selectedProviderSchema.schema?.properties,
  );
 
  return (
    <>
      <PageHeader
        title={mode === 'create' ? 'Add AI Provider' : 'Edit AI Provider'}
        description={
          mode === 'create'
            ? 'Add a new AI provider'
            : 'Update your AI provider configuration'
        }
        onBack={handleBack}
      />
      <div className="p-6 space-y-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <KeyIcon className="h-5 w-5" />
              {mode === 'create' ? 'Add New AI Provider' : 'Edit AI Provider'}
            </CardTitle>
            <CardDescription>
              {mode === 'create'
                ? 'Configure your AI provider. API keys will be encrypted and stored securely.'
                : 'Update your AI provider configuration. Leave the API key field unchanged to keep the existing key.'}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className="space-y-6"
              >
                <FormField
                  control={form.control}
                  name="ai_provider"
                  render={({ field }) => (
                    <FormItem className="flex flex-col">
                      <FormLabel>AI Provider</FormLabel>
                      <Popover
                        open={providerComboboxOpen}
                        onOpenChange={setProviderComboboxOpen}
                      >
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              role="combobox"
                              className="justify-between w-[240px]"
                            >
                              {field.value
                                ? AI_PROVIDERS.find(
                                    (provider) =>
                                      provider.value === field.value,
                                  )?.label
                                : 'Select an AI provider'}
                              <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-[240px] p-0" align="start">
                          <Command>
                            <CommandInput placeholder="Search AI providers..." />
                            <CommandList>
                              <CommandEmpty>No provider found.</CommandEmpty>
                              <CommandGroup>
                                {AI_PROVIDERS.map((provider) => (
                                  <CommandItem
                                    key={provider.value}
                                    value={provider.label}
                                    onSelect={() => {
                                      field.onChange(provider.value);
                                      setProviderComboboxOpen(false);
                                    }}
                                  >
                                    <Check
                                      className={
                                        provider.value === field.value
                                          ? 'mr-2 h-4 w-4 opacity-100'
                                          : 'mr-2 h-4 w-4 opacity-0'
                                      }
                                    />
                                    {provider.label}
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )}
                />
 
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Name</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="e.g., Production Key, Development Key"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
 
                <FormField
                  control={form.control}
                  name="api_key"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        API Key
                        {!(selectedProviderSchema?.isAPIKeyRequired ?? true) &&
                          ' (Optional)'}
                      </FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            type={showAPIKey ? 'text' : 'password'}
                            placeholder="API key to access the provider"
                            {...field}
                            value={field.value ?? ''}
                            className="pr-10"
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-2 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0"
                            onClick={() => setShowAPIKey(!showAPIKey)}
                          >
                            {showAPIKey ? (
                              <EyeOffIcon className="h-4 w-4" />
                            ) : (
                              <EyeIcon className="h-4 w-4" />
                            )}
                          </Button>
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
 
                {!schemasLoading &&
                hasCustomFields &&
                selectedProviderSchema?.schema?.properties
                  ? Object.entries(
                      selectedProviderSchema.schema.properties as Record<
                        string,
                        {
                          type?: string;
                          description?: string;
                          maxLength?: number;
                          format?: string;
                        }
                      >,
                    ).map(([fieldName, fieldSchema]) => {
                      const fieldType = fieldSchema.type;
                      const description = fieldSchema.description;
                      const isRequired =
                        (
                          selectedProviderSchema.schema?.required as
                            | string[]
                            | undefined
                        )?.includes(fieldName) || false;
 
                      return (
                        <FormItem key={fieldName}>
                          <FormLabel>
                            {fieldName
                              .split('_')
                              .map(
                                (word) =>
                                  word.charAt(0).toUpperCase() + word.slice(1),
                              )
                              .join(' ')}
                            {!isRequired && ' (Optional)'}
                          </FormLabel>
                          {description && (
                            <FormDescription className="p-0 m-0">
                              {description}
                            </FormDescription>
                          )}
                          <FormControl>
                            <Input
                              type={
                                fieldSchema.format === 'uri' ? 'url' : 'text'
                              }
                              placeholder={
                                DEFAULT_SELF_HOSTED_URLS[
                                  selectedProvider as AIProvider
                                ] ||
                                (fieldType === 'string'
                                  ? 'Enter value'
                                  : undefined)
                              }
                              value={
                                (form.watch('custom_fields')?.[
                                  fieldName
                                ] as string) || ''
                              }
                              onChange={(e) => {
                                const currentFields =
                                  form.getValues('custom_fields') || {};
                                form.setValue('custom_fields', {
                                  ...currentFields,
                                  [fieldName]: e.target.value || undefined,
                                });
                              }}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      );
                    })
                  : null}
 
                <div className="flex justify-end gap-3">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleBack}
                    disabled={isSubmitting}
                  >
                    Cancel
                  </Button>
                  <Button type="submit" disabled={isSubmitting}>
                    {isSubmitting ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2" />
                        {mode === 'create' ? 'Creating...' : 'Updating...'}
                      </>
                    ) : (
                      <>
                        <SaveIcon className="h-4 w-4 mr-2" />
                        {mode === 'create'
                          ? 'Create AI Provider'
                          : 'Update AI Provider'}
                      </>
                    )}
                  </Button>
                </div>
              </form>
            </Form>
          </CardContent>
        </Card>
      </div>
    </>
  );
}