All files / web/src/components/models model-form.tsx

78.03% Statements 206/264
57.57% Branches 19/33
66.66% Functions 4/6
78.03% Lines 206/264

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    1x           1x         1x 1x             1x                 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x               1x 33x 33x 33x 33x 33x 33x   33x 33x   33x   33x 33x 33x 33x 33x 33x 33x     33x 29x   8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 8x   8x 33x   33x                                                                                             33x 33x 33x   33x 12x 12x 12x 12x 12x 12x 12x     12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x   21x 21x 21x 33x 33x 33x   21x   33x 33x 33x   33x 33x 33x 33x 33x 33x 33x 33x 33x   21x 33x 33x 33x 33x 33x 33x 33x   33x 33x 33x 33x 24x 24x 24x 24x 24x       24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x     24x 24x 24x   24x 33x   33x 33x 33x 33x 22x 22x 22x 22x 22x 22x   22x 22x 22x 22x 22x 2x 20x   20x   22x 22x 22x 22x 22x 22x   22x                             22x 22x 22x 22x   22x 22x 22x 22x   33x   33x 33x 33x 33x 33x 33x 33x   33x 33x 33x 33x   33x     33x 33x 33x 33x 33x 33x 33x 33x 33x   33x  
'use client';
 
import { zodResolver } from '@hookform/resolvers/zod';
import type { AIProvider } from '@shared/types/constants';
import type {
  ModelCreateParams,
  ModelUpdateParams,
} from '@shared/types/data/model';
import {
  createModel,
  getModelById,
  updateModel,
} from '@web/api/v1/super-agents/models';
import { Button } from '@web/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@web/components/ui/card';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@web/components/ui/form';
import { ModelAutocompleteInput } from '@web/components/ui/model-autocomplete-input';
import { PageHeader } from '@web/components/ui/page-header';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@web/components/ui/select';
import { Skeleton } from '@web/components/ui/skeleton';
import { usePermissiveNavigate } from '@web/hooks/use-permissive-navigate';
import { useSmartBack } from '@web/hooks/use-smart-back';
import { useToast } from '@web/hooks/use-toast';
import { useAIProviders } from '@web/providers/ai-providers';
import { useModels } from '@web/providers/models';
import { CpuIcon, LoaderIcon } from 'lucide-react';
import type { ReactElement } from 'react';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
 
const modelFormSchema = z.object({
  model_name: z.string().min(1, 'Model name is required'),
  ai_provider_id: z.string().uuid('Please select a valid AI provider API key'),
});
 
type ModelFormData = z.infer<typeof modelFormSchema>;
 
interface ModelFormProps {
  modelId?: string;
}
 
export function ModelForm({ modelId }: ModelFormProps): ReactElement {
  const navigate = usePermissiveNavigate();
  const goBack = useSmartBack();
  const { toast } = useToast();
  const { refetch } = useModels();
  const { aiProviderConfigs: apiKeys, isLoading: isLoadingAPIKeys } =
    useAIProviders();
 
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingModel, setIsLoadingModel] = useState(!!modelId);
 
  const isEdit = !!modelId;
 
  const form = useForm<ModelFormData>({
    resolver: zodResolver(modelFormSchema),
    defaultValues: {
      model_name: '',
      ai_provider_id: '',
    },
  });
 
  // Load existing model data for editing
  useEffect(() => {
    if (!modelId) return;
 
    const loadModel = async () => {
      try {
        setIsLoadingModel(true);
        const model = await getModelById(modelId);
 
        form.reset({
          model_name: model.model_name,
          ai_provider_id: model.ai_provider_id,
        });
      } catch (error) {
        toast({
          title: 'Failed to load model',
          description:
            error instanceof Error
              ? error.message
              : 'An unexpected error occurred.',
          variant: 'destructive',
        });
        goBack();
      } finally {
        setIsLoadingModel(false);
      }
    };
 
    loadModel();
  }, [modelId, form, toast, goBack]);
 
  const onSubmit = async (data: ModelFormData) => {
    try {
      setIsLoading(true);
 
      if (isEdit && modelId) {
        const updateData: ModelUpdateParams = {
          model_name: data.model_name,
        };
        await updateModel(modelId, updateData);
 
        toast({
          title: 'Model updated',
          description: `Model "${data.model_name}" has been updated successfully.`,
        });
      } else {
        const createData: ModelCreateParams = {
          model_name: data.model_name,
          ai_provider_id: data.ai_provider_id,
          model_type: 'text',
        };
        await createModel(createData);
 
        toast({
          title: 'Model created',
          description: `Model "${data.model_name}" has been created successfully.`,
        });
 
        // Reset form after successful creation to clear data
        form.reset();
      }
 
      await refetch();
      navigate({ to: '/models' });
    } catch (error) {
      toast({
        title: isEdit ? 'Failed to update model' : 'Failed to create model',
        description:
          error instanceof Error
            ? error.message
            : 'An unexpected error occurred.',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };
 
  const availableAPIKeys = apiKeys.filter(
    (apiKey) => apiKey.ai_provider && apiKey.name,
  );
 
  if (isLoadingModel) {
    return (
      <>
        <PageHeader
          title={isEdit ? 'Edit Model' : 'Add Model'}
          description={
            isEdit
              ? 'Update model configuration'
              : 'Add a new AI model to your workspace'
          }
          showBackButton={true}
          onBack={goBack}
        />
        <div className="p-6">
          <Card>
            <CardHeader>
              <Skeleton className="h-6 w-48" />
              <Skeleton className="h-4 w-96" />
            </CardHeader>
            <CardContent className="space-y-4">
              <Skeleton className="h-20 w-full" />
              <Skeleton className="h-20 w-full" />
              <Skeleton className="h-10 w-32" />
            </CardContent>
          </Card>
        </div>
      </>
    );
  }
 
  return (
    <>
      <PageHeader
        title={isEdit ? 'Edit Model' : 'Add Model'}
        description={
          isEdit
            ? 'Update model configuration'
            : 'Add a new AI model to your workspace'
        }
        showBackButton={true}
        onBack={goBack}
      />
 
      <div className="p-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CpuIcon className="h-5 w-5" />
              {isEdit ? 'Update Model' : 'Create New Model'}
            </CardTitle>
            <CardDescription>
              {isEdit
                ? 'Update the configuration for this AI model.'
                : 'Configure a new AI model for use in your workspace.'}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className="space-y-6"
              >
                <FormField
                  control={form.control}
                  name="model_name"
                  render={({ field }) => {
                    const selectedProviderId = form.watch('ai_provider_id');
                    const selectedProvider = availableAPIKeys.find(
                      (key) => key.id === selectedProviderId,
                    );
                    const provider = selectedProvider?.ai_provider as
                      | AIProvider
                      | undefined;
 
                    return (
                      <FormItem>
                        <FormLabel>Model Name</FormLabel>
                        <FormControl>
                          <ModelAutocompleteInput
                            value={field.value}
                            onChange={field.onChange}
                            onBlur={field.onBlur}
                            provider={provider}
                            placeholder="e.g., gpt-5, claude-sonnet-4-5, gemini-2.5-pro"
                            disabled={isEdit}
                            aria-invalid={!!form.formState.errors.model_name}
                          />
                        </FormControl>
                        <FormDescription>
                          The name of the AI model as provided by the AI
                          provider.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    );
                  }}
                />
 
                <FormField
                  control={form.control}
                  name="ai_provider_id"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>AI Provider API Key</FormLabel>
                      <Select
                        onValueChange={field.onChange}
                        value={field.value}
                        disabled={isEdit || isLoadingAPIKeys}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue
                              placeholder={
                                isLoadingAPIKeys
                                  ? 'Loading API keys...'
                                  : isEdit
                                    ? 'API key cannot be changed'
                                    : 'Select an API key'
                              }
                            />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {availableAPIKeys.length === 0 ? (
                            <SelectItem value="no-keys" disabled>
                              No API keys available
                            </SelectItem>
                          ) : (
                            availableAPIKeys.map((apiKey) => (
                              <SelectItem key={apiKey.id} value={apiKey.id}>
                                <div className="flex flex-col">
                                  <span className="font-medium">
                                    {apiKey.name}
                                  </span>
                                  <span className="text-sm text-muted-foreground">
                                    {apiKey.ai_provider}
                                  </span>
                                </div>
                              </SelectItem>
                            ))
                          )}
                        </SelectContent>
                      </Select>
                      <FormDescription>
                        {isEdit
                          ? 'The API key associated with this model cannot be changed.'
                          : 'Select the API key that will be used to access this model.'}
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
 
                <div className="flex justify-end space-x-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => goBack()}
                    disabled={isLoading}
                  >
                    Cancel
                  </Button>
                  <Button
                    type="submit"
                    disabled={isLoading || (isLoadingAPIKeys && !isEdit)}
                  >
                    {isLoading && (
                      <LoaderIcon className="h-4 w-4 mr-2 animate-spin" />
                    )}
                    {isEdit ? 'Update Model' : 'Create Model'}
                  </Button>
                </div>
              </form>
            </Form>
          </CardContent>
        </Card>
      </div>
    </>
  );
}