All files / web/src/providers skills.tsx

69.94% Statements 135/193
91.3% Branches 21/23
33.33% Functions 6/18
69.94% Lines 135/193

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                1x           1x           1x 1x 1x   1x                 1x 1x 1x 1x 89x 1x 1x 1x                                                                         1x   1x 89x 89x   89x 89x 89x 89x 89x   89x     89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 50x 50x 50x 50x 50x 89x 71x 71x 59x 59x 12x 71x 89x 89x     89x     89x 89x 89x 89x 89x 89x 89x 89x                 89x 89x 89x     89x 51x 6x 89x     89x 89x 89x                 89x               89x     89x 89x             89x                 89x               89x     89x 89x 89x                 89x               89x     89x 89x 2x 2x 89x 89x   89x   89x     89x 89x     89x 89x   89x 89x     89x 89x   89x 89x     89x 89x   89x   89x 89x 89x 89x 89x     89x 89x     89x 89x 89x     89x 89x 89x 89x 89x 89x     89x 89x 89x     89x 89x 89x   89x 89x 89x 89x   89x   1x 22x 22x 2x 2x 20x 20x  
'use client';
 
import type {
  Skill,
  SkillCreateParams,
  SkillQueryParams,
  SkillUpdateParams,
} from '@shared/types/data/skill';
import {
  useInfiniteQuery,
  useMutation,
  useQuery,
  useQueryClient,
} from '@tanstack/react-query';
import {
  createSkill,
  deleteSkill,
  getSkills,
  updateSkill,
} from '@web/api/v1/super-agents/skills';
import { useToast } from '@web/hooks/use-toast';
import { useAgents } from '@web/providers/agents';
import { useNavigation } from '@web/providers/navigation';
import type React from 'react';
import {
  createContext,
  useCallback,
  useContext,
  useMemo,
  useState,
} from 'react';
 
// Query keys for React Query caching
export const skillQueryKeys = {
  all: ['skills'] as const,
  lists: () => [...skillQueryKeys.all, 'list'] as const,
  list: (params: SkillQueryParams) =>
    [...skillQueryKeys.lists(), params] as const,
  details: () => [...skillQueryKeys.all, 'detail'] as const,
  detail: (id: string) => [...skillQueryKeys.details(), id] as const,
};
 
interface SkillsContextType {
  // Query state
  skills: Skill[];
  selectedSkill?: Skill;
  isLoading: boolean;
  error: Error | null;
  refetch: () => void;
 
  // Query parameters
  queryParams: SkillQueryParams;
  setQueryParams: (params: SkillQueryParams) => void;
 
  // Skill mutation functions
  createSkill: (params: SkillCreateParams) => Promise<Skill>;
  updateSkill: (skillId: string, params: SkillUpdateParams) => Promise<void>;
  deleteSkill: (skillId: string) => Promise<void>;
 
  // Skill mutation states
  isCreating: boolean;
  isUpdating: boolean;
  isDeleting: boolean;
  createError: Error | null;
  updateError: Error | null;
  deleteError: Error | null;
 
  // Pagination
  hasNextPage: boolean;
  isFetchingNextPage: boolean;
  fetchNextPage: () => void;
 
  // Helper functions
  getSkillById: (id: string) => Skill | undefined;
  refreshSkills: () => void;
}
 
const SkillsContext = createContext<SkillsContextType | undefined>(undefined);
 
export const SkillsProvider = ({
  children,
}: {
  children: React.ReactNode;
}): React.ReactElement => {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const { navigationState } = useNavigation();
  const { selectedAgent } = useAgents();
 
  const [queryParams, setQueryParams] = useState<SkillQueryParams>({});
 
  // Skills infinite query for pagination
  const {
    data,
    isLoading,
    error,
    refetch,
    hasNextPage,
    isFetchingNextPage,
    fetchNextPage,
  } = useInfiniteQuery({
    queryKey: skillQueryKeys.list(queryParams),
    queryFn: ({ pageParam = 0 }) =>
      getSkills({
        ...queryParams,
        limit: queryParams.limit || 20,
        offset: pageParam,
      }),
    getNextPageParam: (lastPage, allPages) => {
      const currentLength = allPages.flat().length;
      if (lastPage.length < (queryParams.limit || 20)) {
        return undefined;
      }
      return currentLength;
    },
    initialPageParam: 0,
  });
 
  // Flatten pages into single array
  const skills: Skill[] = data?.pages?.flat() ?? [];
 
  // Fetch individual skill by name when URL has a selected skill
  const { data: selectedSkillData } = useQuery({
    queryKey: [
      'skill',
      'by-name',
      navigationState.selectedSkillName,
      selectedAgent?.id,
    ],
    queryFn: async () => {
      if (!selectedAgent?.id) return undefined;
      const results = await getSkills({
        name: navigationState.selectedSkillName,
        agent_id: selectedAgent.id,
        limit: 1,
      });
      return results.length > 0 ? results[0] : undefined;
    },
    enabled: !!navigationState.selectedSkillName && !!selectedAgent?.id,
    staleTime: 0, // Refetch immediately when invalidated
  });
 
  // Resolve selectedSkill from navigationState.selectedSkillName
  const selectedSkill = useMemo(() => {
    if (!navigationState.selectedSkillName) return undefined;
    return selectedSkillData;
  }, [navigationState.selectedSkillName, selectedSkillData]);
 
  // Create skill mutation
  const createSkillMutation = useMutation({
    mutationFn: (params: SkillCreateParams) => createSkill(params),
    onSuccess: (newSkill) => {
      // Invalidate all lists to ensure consistency
      queryClient.invalidateQueries({ queryKey: skillQueryKeys.lists() });
 
      toast({
        title: 'Skill created',
        description: `${newSkill.name} has been created successfully.`,
      });
    },
    onError: (error) => {
      console.error('Error creating skill:', error);
      toast({
        title: 'Error creating skill',
        description: 'Please try again later',
        variant: 'destructive',
      });
    },
  });
 
  // Update skill mutation
  const updateSkillMutation = useMutation({
    mutationFn: ({
      skillId,
      params,
    }: {
      skillId: string;
      params: SkillUpdateParams;
    }) => updateSkill(skillId, params),
    onSuccess: (updatedSkill: Skill) => {
      // Invalidate all skill queries to ensure UI reflects changes
      queryClient.invalidateQueries({ queryKey: skillQueryKeys.all });
 
      toast({
        title: 'Skill updated',
        description: `${updatedSkill.name} has been updated successfully.`,
      });
    },
    onError: (error) => {
      console.error('Error updating skill:', error);
      toast({
        title: 'Error updating skill',
        description: 'Please try again later',
        variant: 'destructive',
      });
    },
  });
 
  // Delete skill mutation
  const deleteSkillMutation = useMutation({
    mutationFn: (skillId: string) => deleteSkill(skillId),
    onSuccess: () => {
      // Invalidate lists to ensure consistency
      queryClient.invalidateQueries({ queryKey: skillQueryKeys.lists() });
 
      toast({
        title: 'Skill deleted',
        description: 'Skill has been deleted successfully.',
      });
    },
    onError: (error) => {
      console.error('Error deleting skill:', error);
      toast({
        title: 'Error deleting skill',
        description: 'Please try again later',
        variant: 'destructive',
      });
    },
  });
 
  // Helper functions
  const getSkillById = useCallback(
    (id: string): Skill | undefined => {
      return skills?.find((skill) => skill.id === id);
    },
    [skills],
  );
 
  const refreshSkills = useCallback(() => {
    queryClient.invalidateQueries({ queryKey: skillQueryKeys.all });
  }, [queryClient]);
 
  // Simplified mutation functions
  const createSkillHandler = useCallback(
    (params: SkillCreateParams): Promise<Skill> => {
      return createSkillMutation.mutateAsync(params);
    },
    [createSkillMutation],
  );
 
  const updateSkillHandler = useCallback(
    async (skillId: string, params: SkillUpdateParams): Promise<void> => {
      await updateSkillMutation.mutateAsync({ skillId, params });
    },
    [updateSkillMutation],
  );
 
  const deleteSkillHandler = useCallback(
    async (skillId: string): Promise<void> => {
      await deleteSkillMutation.mutateAsync(skillId);
    },
    [deleteSkillMutation],
  );
 
  const contextValue: SkillsContextType = {
    // Query state
    skills,
    selectedSkill,
    isLoading,
    error,
    refetch,
 
    // Query parameters
    queryParams,
    setQueryParams,
 
    // Skill mutation functions
    createSkill: createSkillHandler,
    updateSkill: updateSkillHandler,
    deleteSkill: deleteSkillHandler,
 
    // Skill mutation states
    isCreating: createSkillMutation.isPending,
    isUpdating: updateSkillMutation.isPending,
    isDeleting: deleteSkillMutation.isPending,
    createError: createSkillMutation.error,
    updateError: updateSkillMutation.error,
    deleteError: deleteSkillMutation.error,
 
    // Pagination
    hasNextPage: hasNextPage ?? false,
    isFetchingNextPage,
    fetchNextPage,
 
    // Helper functions
    getSkillById,
    refreshSkills,
  };
 
  return (
    <SkillsContext.Provider value={contextValue}>
      {children}
    </SkillsContext.Provider>
  );
};
 
export const useSkills = (): SkillsContextType => {
  const context = useContext(SkillsContext);
  if (!context) {
    throw new Error('useSkills must be used within a SkillsProvider');
  }
  return context;
};