All files / web/src/providers agents.tsx

98.12% Statements 209/213
89.58% Branches 43/48
100% Functions 24/24
98.12% Lines 209/213

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                1x           1x           1x 1x 1x   1x                 1x 1x 1x 1x 162x 1x 1x 1x                                                                                 1x   1x 161x 161x   161x 161x 161x 161x 161x   161x 161x     161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 161x 84x 84x 84x 84x 84x 161x 165x 165x 165x 165x   165x 161x 161x     161x 104x   104x     104x 161x     161x 161x 161x 36x 36x 36x 36x 36x 36x 161x 161x 161x     161x 107x 47x 161x     161x 161x 161x   2x   2x 2x 2x 2x 2x 161x 1x 1x 1x 1x 1x 1x 1x 161x     161x 161x 2x 2x 2x     2x 161x   1x   1x 1x 1x 1x 1x 161x 1x 1x 1x 1x 1x 1x 1x 161x     161x 161x 161x   3x   3x 3x 3x 3x 3x 161x 1x 1x 1x 1x 1x 1x 1x 161x     161x 161x 1x 1x 161x 161x   161x   161x     161x 161x 3x 3x 3x 3x 3x 3x 3x 161x 161x   161x 161x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 161x 161x   161x 161x 4x 4x 4x 4x 4x 4x 4x 161x 161x   161x   161x 161x 161x 161x 161x     161x 161x     161x 161x 161x     161x 161x 161x 161x 161x 161x     161x 161x 161x     161x 161x     161x 161x 161x   161x 161x 161x 161x   161x   1x 177x 177x 2x 2x 174x 174x  
'use client';
 
import type {
  Agent,
  AgentCreateParams,
  AgentQueryParams,
  AgentUpdateParams,
} from '@shared/types/data';
import {
  useInfiniteQuery,
  useMutation,
  useQuery,
  useQueryClient,
} from '@tanstack/react-query';
import {
  createAgent,
  deleteAgent,
  getAgents,
  updateAgent,
} from '@web/api/v1/super-agents/agents';
import { useToast } from '@web/hooks/use-toast';
import { useNavigation } from '@web/providers/navigation';
import { useSystemSettings } from '@web/providers/system-settings';
import type React from 'react';
import {
  createContext,
  useCallback,
  useContext,
  useMemo,
  useState,
} from 'react';
 
// Query keys for React Query caching
export const agentQueryKeys = {
  all: ['agents'] as const,
  lists: () => [...agentQueryKeys.all, 'list'] as const,
  list: (params: AgentQueryParams) =>
    [...agentQueryKeys.lists(), params] as const,
  details: () => [...agentQueryKeys.all, 'detail'] as const,
  detail: (id: string) => [...agentQueryKeys.details(), id] as const,
};
 
interface AgentsContextType {
  // Query state
  agents: Agent[];
  selectedAgent?: Agent;
  isLoading: boolean;
  error: Error | null;
  refetch: () => void;
 
  // Query parameters
  queryParams: AgentQueryParams;
  setQueryParams: (params: AgentQueryParams) => void;
 
  // Mutation functions
  createAgent: (params: AgentCreateParams) => Promise<Agent>;
  updateAgent: (agentId: string, params: AgentUpdateParams) => Promise<void>;
  deleteAgent: (agentId: string) => Promise<void>;
 
  // Separate 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
  getAgentById: (id: string) => Agent | undefined;
  refreshAgents: () => void;
 
  // Create Agent UI
  isCreateAgentDialogOpen: boolean;
  setIsCreateAgentDialogOpen: (isOpen: boolean) => void;
}
 
const AgentsContext = createContext<AgentsContextType | undefined>(undefined);
 
export const AgentsProvider = ({
  children,
}: {
  children: React.ReactNode;
}): React.ReactElement => {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const { navigationState } = useNavigation();
  const { settings } = useSystemSettings();
 
  const [queryParams, setQueryParams] = useState<AgentQueryParams>({});
  const [isCreateAgentDialogOpen, setIsCreateAgentDialogOpen] = useState(false);
 
  // Infinite query for paginated results
  const {
    data,
    isLoading,
    error,
    refetch,
    hasNextPage,
    isFetchingNextPage,
    fetchNextPage,
  } = useInfiniteQuery({
    queryKey: agentQueryKeys.list(queryParams),
    queryFn: ({ pageParam = 0 }) =>
      getAgents({
        ...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 and conditionally filter internal agents
  const agents: Agent[] = useMemo(() => {
    const allAgents = data?.pages?.flat() ?? [];
    // Show all agents when developer mode is enabled, otherwise filter out internal agents
    if (settings?.developer_mode) {
      return allAgents;
    }
    return allAgents.filter((agent) => agent.name !== 'super-agents');
  }, [data, settings?.developer_mode]);
 
  // Fetch individual agent by name when URL has a selected agent
  const { data: selectedAgentData } = useQuery({
    queryKey: ['agent', 'by-name', navigationState.selectedAgentName],
    queryFn: async () => {
      const results = await getAgents({
        name: navigationState.selectedAgentName,
        limit: 1,
      });
      return results.length > 0 ? results[0] : undefined;
    },
    enabled: !!navigationState.selectedAgentName,
    staleTime: 0, // Refetch immediately when invalidated
  });
 
  // Resolve selectedAgent from navigationState.selectedAgentName
  const selectedAgent = useMemo(() => {
    if (!navigationState.selectedAgentName) return undefined;
    return selectedAgentData;
  }, [navigationState.selectedAgentName, selectedAgentData]);
 
  // Create agent mutation
  const createAgentMutation = useMutation({
    mutationFn: (params: AgentCreateParams) => createAgent(params),
    onSuccess: (newAgent) => {
      // Invalidate all lists to ensure consistency
      queryClient.invalidateQueries({ queryKey: agentQueryKeys.lists() });
 
      toast({
        title: 'Agent created',
        description: `${newAgent.name} has been created successfully.`,
      });
    },
    onError: (error) => {
      console.error('Error creating agent:', error);
      toast({
        title: 'Error creating agent',
        description: 'Please try again later',
        variant: 'destructive',
      });
    },
  });
 
  // Update agent mutation
  const updateAgentMutation = useMutation({
    mutationFn: ({
      agentId,
      params,
    }: {
      agentId: string;
      params: AgentUpdateParams;
    }) => updateAgent(agentId, params),
    onSuccess: (updatedAgent) => {
      // Invalidate queries to ensure consistency
      queryClient.invalidateQueries({ queryKey: agentQueryKeys.lists() });
 
      toast({
        title: 'Agent updated',
        description: `${updatedAgent.name} has been updated successfully.`,
      });
    },
    onError: (error) => {
      console.error('Error updating agent:', error);
      toast({
        title: 'Error updating agent',
        description: 'Please try again later',
        variant: 'destructive',
      });
    },
  });
 
  // Delete agent mutation
  const deleteAgentMutation = useMutation({
    mutationFn: (agentId: string) => deleteAgent(agentId),
    onSuccess: () => {
      // Invalidate lists to ensure consistency
      queryClient.invalidateQueries({ queryKey: agentQueryKeys.lists() });
 
      toast({
        title: 'Agent deleted',
        description: 'Agent has been deleted successfully.',
      });
    },
    onError: (error) => {
      console.error('Error deleting agent:', error);
      toast({
        title: 'Error deleting agent',
        description: 'Please try again later',
        variant: 'destructive',
      });
    },
  });
 
  // Helper functions
  const getAgentById = useCallback(
    (id: string): Agent | undefined => {
      return agents?.find((agent: Agent) => agent.id === id);
    },
    [agents],
  );
 
  const refreshAgents = useCallback(() => {
    queryClient.invalidateQueries({ queryKey: agentQueryKeys.all });
  }, [queryClient]);
 
  // Simplified mutation functions
  const createAgentHandler = useCallback(
    (params: AgentCreateParams): Promise<Agent> => {
      return new Promise((resolve, reject) => {
        createAgentMutation.mutate(params, {
          onSuccess: (agent) => resolve(agent),
          onError: (error) => reject(error),
        });
      });
    },
    [createAgentMutation],
  );
 
  const updateAgentHandler = useCallback(
    (agentId: string, params: AgentUpdateParams): Promise<void> => {
      return new Promise((resolve, reject) => {
        updateAgentMutation.mutate(
          { agentId, params },
          {
            onSuccess: () => resolve(),
            onError: (error) => reject(error),
          },
        );
      });
    },
    [updateAgentMutation],
  );
 
  const deleteAgentHandler = useCallback(
    (agentId: string): Promise<void> => {
      return new Promise((resolve, reject) => {
        deleteAgentMutation.mutate(agentId, {
          onSuccess: () => resolve(),
          onError: (error) => reject(error),
        });
      });
    },
    [deleteAgentMutation],
  );
 
  const contextValue: AgentsContextType = {
    // Query state
    agents,
    selectedAgent,
    isLoading,
    error,
    refetch,
 
    // Query parameters
    queryParams,
    setQueryParams,
 
    // Simplified mutation functions
    createAgent: createAgentHandler,
    updateAgent: updateAgentHandler,
    deleteAgent: deleteAgentHandler,
 
    // Separate mutation states
    isCreating: createAgentMutation.isPending,
    isUpdating: updateAgentMutation.isPending,
    isDeleting: deleteAgentMutation.isPending,
    createError: createAgentMutation.error,
    updateError: updateAgentMutation.error,
    deleteError: deleteAgentMutation.error,
 
    // Pagination
    hasNextPage: hasNextPage ?? false,
    isFetchingNextPage,
    fetchNextPage,
 
    // Helper functions
    getAgentById,
    refreshAgents,
 
    // Create Agent UI
    isCreateAgentDialogOpen,
    setIsCreateAgentDialogOpen,
  };
 
  return (
    <AgentsContext.Provider value={contextValue}>
      {children}
    </AgentsContext.Provider>
  );
};
 
export const useAgents = (): AgentsContextType => {
  const context = useContext(AgentsContext);
  if (!context) {
    throw new Error('useAgents must be used within an AgentsProvider');
  }
  return context;
};