All files / web/src/components/agents/skills manage-skill-models-dialog.tsx

72.84% Statements 169/232
64% Branches 16/25
25% Functions 2/8
72.84% Lines 169/232

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    1x   1x 1x       1x 1x 1x 1x 1x               1x 1x 1x 1x 1x   1x               1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   14x 14x 14x 14x 14x 14x 14x     14x 7x 7x 7x 7x     14x     14x 7x   7x 7x 7x 14x   14x                       14x                                                                                                           14x           14x 14x 14x   14x 14x     14x 10x 10x 10x   10x 10x 10x     14x     14x 14x 20x 10x 10x 20x 20x 20x 14x 14x     14x 10x 10x 10x 10x     14x 14x         14x   14x 14x 14x 14x 14x 14x   14x 14x     14x 14x   14x 14x 2x 2x 2x 2x 2x 2x 12x 2x 2x 2x   2x 2x     2x 2x   10x 10x 10x   10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 20x 20x 20x 20x   20x 20x 20x   20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 10x 10x   10x   14x   14x 14x 14x 14x   14x 14x 14x 14x 14x 14x   14x 14x 14x           14x   14x 14x 14x 14x   14x  
'use client';
 
import { type AIProvider, PrettyAIProvider } from '@shared/types/constants';
import type { Model } from '@shared/types/data/model';
import { useQueryClient } from '@tanstack/react-query';
import {
  addModelsToSkill,
  removeModelsFromSkill,
} from '@web/api/v1/super-agents/skills';
import { Badge } from '@web/components/ui/badge';
import { Button } from '@web/components/ui/button';
import { Card, CardContent } from '@web/components/ui/card';
import { Checkbox } from '@web/components/ui/checkbox';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@web/components/ui/dialog';
import { useToast } from '@web/hooks/use-toast';
import { useAIProviders } from '@web/providers/ai-providers';
import { useModels } from '@web/providers/models';
import { compareModels } from '@web/utils/model-sorting';
import { Clock, CpuIcon, Loader2 } from 'lucide-react';
import type { ReactElement } from 'react';
import { useEffect, useState } from 'react';
 
interface ManageSkillModelsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  skillId: string;
}
 
export function ManageSkillModelsDialog({
  open,
  onOpenChange,
  skillId,
}: ManageSkillModelsDialogProps): ReactElement {
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const { aiProviderConfigs: apiKeys } = useAIProviders();
  const {
    models,
    isLoading: isLoadingAllModels,
    setQueryParams,
    skillModels,
    isLoadingSkillModels,
    setSkillId: setModelsSkillId,
    refetchSkillModels,
  } = useModels();
 
  const [initialModelIds, setInitialModelIds] = useState<Set<string>>(
    new Set(),
  );
  const [selectedModelIds, setSelectedModelIds] = useState<Set<string>>(
    new Set(),
  );
  const [isSaving, setIsSaving] = useState(false);
 
  // Load all models and skill models when dialog opens
  useEffect(() => {
    if (open && skillId) {
      setQueryParams({});
      setModelsSkillId(skillId);
    } else if (!open) {
      setModelsSkillId(null);
    }
  }, [open, skillId, setQueryParams, setModelsSkillId]);
 
  // Update selected models when skill models change
  useEffect(() => {
    if (!open) return;
 
    const ids = new Set(skillModels.map((model) => model.id));
    setInitialModelIds(ids);
    setSelectedModelIds(ids);
  }, [skillModels, open]);
 
  const handleToggleModel = (modelId: string) => {
    setSelectedModelIds((prev) => {
      const next = new Set(prev);
      if (next.has(modelId)) {
        next.delete(modelId);
      } else {
        next.add(modelId);
      }
      return next;
    });
  };
 
  const handleSave = async () => {
    setIsSaving(true);
    try {
      // Determine what to add and what to remove
      const modelsToAdd = Array.from(selectedModelIds).filter(
        (id) => !initialModelIds.has(id),
      );
      const modelsToRemove = Array.from(initialModelIds).filter(
        (id) => !selectedModelIds.has(id),
      );
 
      const operations = [];
 
      if (modelsToRemove.length > 0) {
        operations.push(removeModelsFromSkill(skillId, modelsToRemove));
      }
 
      if (modelsToAdd.length > 0) {
        operations.push(addModelsToSkill(skillId, modelsToAdd));
      }
 
      // Execute all operations in parallel
      await Promise.all(operations);
 
      toast({
        title: 'Models updated successfully',
        description: `Updated models for the skill.`,
      });
 
      // Invalidate the skill validation cache to refresh the UI
      await queryClient.invalidateQueries({
        queryKey: ['skill-validation-models', skillId],
      });
 
      // Refresh skill models
      await refetchSkillModels();
 
      // Close dialog on success
      onOpenChange(false);
    } catch (error) {
      console.error('Failed to save model changes:', error);
      toast({
        title: 'Failed to update models',
        description:
          error instanceof Error
            ? error.message
            : 'An unexpected error occurred.',
        variant: 'destructive',
      });
    } finally {
      setIsSaving(false);
    }
  };
 
  const handleCancel = () => {
    // Reset to initial state
    setSelectedModelIds(initialModelIds);
    onOpenChange(false);
  };
 
  const hasChanges =
    Array.from(selectedModelIds).sort().join(',') !==
    Array.from(initialModelIds).sort().join(',');
 
  const isProcessing = isSaving;
  const isLoading = isLoadingAllModels || isLoadingSkillModels;
 
  // Get provider info
  const getProviderInfo = (apiKeyId: string) => {
    const apiKey = apiKeys.find((key) => key.id === apiKeyId);
    const providerType = apiKey
      ? PrettyAIProvider[apiKey.ai_provider as AIProvider] || apiKey.ai_provider
      : 'Unknown Provider';
    const providerName = apiKey?.name || 'Unknown';
    return { providerType, providerName };
  };
 
  // Filter out embedding models - only show text models for skills
  const textModels = models.filter((model) => model.model_type === 'text');
 
  // Group models by provider, with models sorted alphabetically within each group
  const modelsByProvider = textModels.reduce(
    (acc, model) => {
      if (!acc[model.ai_provider_id]) {
        acc[model.ai_provider_id] = [];
      }
      acc[model.ai_provider_id].push(model);
      return acc;
    },
    {} as Record<string, Model[]>,
  );
 
  // Sort models within each provider group by model name
  for (const providerId of Object.keys(modelsByProvider)) {
    modelsByProvider[providerId].sort((a, b) =>
      compareModels({ modelName: a.model_name }, { modelName: b.model_name }),
    );
  }
 
  // Sort provider groups alphabetically by provider name
  const sortedProviderEntries = Object.entries(modelsByProvider).sort(
    ([providerIdA], [providerIdB]) => {
      const { providerName: nameA } = getProviderInfo(providerIdA);
      const { providerName: nameB } = getProviderInfo(providerIdB);
      return nameA.toLowerCase().localeCompare(nameB.toLowerCase());
    },
  );
 
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <CpuIcon size={20} />
            Manage Models
          </DialogTitle>
          <DialogDescription>
            Select models from your configured AI providers. You need at least
            one model for your skill to work.
          </DialogDescription>
        </DialogHeader>
 
        <div className="space-y-3 border rounded-md p-3 max-h-[400px] overflow-y-auto">
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2
                size={24}
                className="animate-spin text-muted-foreground"
              />
            </div>
          ) : sortedProviderEntries.length === 0 ? (
            <div className="text-center py-8">
              <CpuIcon className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-lg font-semibold mb-2">
                No models available
              </h3>
              <p className="text-muted-foreground">
                You need to add AI models first. Go to AI Providers to add
                models.
              </p>
            </div>
          ) : (
            sortedProviderEntries.map(([providerId, providerModels]) => {
              const { providerType, providerName } =
                getProviderInfo(providerId);
 
              return (
                <div key={providerId} className="space-y-2">
                  <div className="flex items-center gap-2 mb-2">
                    <span className="text-sm font-medium">{providerName}</span>
                    <Badge variant="secondary">{providerType}</Badge>
                    <span className="text-xs text-muted-foreground">
                      • {providerModels.length} model(s)
                    </span>
                  </div>
                  {providerModels.map((model) => (
                    <Card
                      key={model.id}
                      className={`cursor-pointer transition-all ${
                        selectedModelIds.has(model.id)
                          ? 'border-primary bg-primary/5'
                          : 'hover:border-primary/50'
                      } ${isProcessing ? 'opacity-50 pointer-events-none' : ''}`}
                      onClick={() => handleToggleModel(model.id)}
                    >
                      <CardContent className="p-3">
                        <div className="flex items-center gap-3">
                          <Checkbox
                            checked={selectedModelIds.has(model.id)}
                            onCheckedChange={() => handleToggleModel(model.id)}
                            onClick={(e) => e.stopPropagation()}
                            disabled={isProcessing}
                          />
                          <div className="flex-1 min-w-0">
                            <div className="font-medium truncate">
                              {model.model_name}
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              );
            })
          )}
        </div>
 
        <div className="flex items-center gap-2 text-sm text-amber-600 dark:text-amber-500 mb-4">
          <Clock size={16} />
          <span>This process may take 1-2 minutes to complete.</span>
        </div>
 
        <DialogFooter>
          <Button
            variant="outline"
            onClick={handleCancel}
            disabled={isProcessing}
          >
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={!hasChanges || isProcessing}>
            {isSaving ? (
              <>
                <Loader2 size={16} className="mr-2 animate-spin" />
                Saving...
              </>
            ) : (
              'Save Changes'
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}