@@ -2,7 +2,13 @@ import { ChatProviderIdEnum, EmailProviderIdEnum } from '@novu/shared';
22import { useQuery , useQueryClient } from '@tanstack/react-query' ;
33import { useCallback , useEffect , useMemo , useState } from 'react' ;
44import { RiExpandUpDownLine } from 'react-icons/ri' ;
5- import { type AgentResponse , getAgentIntegrationsQueryKey , listAgentIntegrations } from '@/api/agents' ;
5+ import {
6+ type AgentResponse ,
7+ getAgentDetailQueryKey ,
8+ getAgentIntegrationsQueryKey ,
9+ listAgentIntegrations ,
10+ removeAgentIntegration ,
11+ } from '@/api/agents' ;
612import { requireEnvironment , useEnvironment } from '@/context/environment/hooks' ;
713import { useFetchIntegrations } from '@/hooks/use-fetch-integrations' ;
814import { cn } from '@/utils/ui' ;
@@ -102,6 +108,35 @@ export function AgentSetupGuide({ agent }: AgentSetupGuideProps) {
102108 } ) ;
103109 } , [ queryClient , currentEnvironment ?. _id , agent . identifier ] ) ;
104110
111+ const handleProviderSelect = useCallback (
112+ ( _providerId : string , integration : { _id : string } | undefined ) => {
113+ if ( ! integration ?. _id || ! currentEnvironment ) return ;
114+
115+ setSelectedIntegrationId ( integration . _id ) ;
116+ sessionStorage . setItem ( SESSION_KEY ( agent . identifier ) , integration . _id ) ;
117+
118+ const staleLinks = ( agentIntegrationsQuery . data ?. data ?? [ ] ) . filter (
119+ ( link ) => ! link . connectedAt && link . integration . _id !== integration . _id
120+ ) ;
121+
122+ if ( ! staleLinks . length ) return ;
123+
124+ void Promise . all (
125+ staleLinks . map ( ( link ) =>
126+ removeAgentIntegration ( currentEnvironment , agent . identifier , link . _id ) . catch ( ( ) => { } )
127+ )
128+ ) . then ( ( ) => {
129+ queryClient . invalidateQueries ( {
130+ queryKey : getAgentIntegrationsQueryKey ( currentEnvironment . _id , agent . identifier ) ,
131+ } ) ;
132+ queryClient . invalidateQueries ( {
133+ queryKey : getAgentDetailQueryKey ( currentEnvironment . _id , agent . identifier ) ,
134+ } ) ;
135+ } ) ;
136+ } ,
137+ [ agent . identifier , agentIntegrationsQuery . data ?. data , currentEnvironment , queryClient ]
138+ ) ;
139+
105140 return (
106141 < div className = "bg-bg-weak flex min-w-0 flex-1 flex-col rounded-[10px] p-1" >
107142 < button
@@ -134,12 +169,7 @@ export function AgentSetupGuide({ agent }: AgentSetupGuideProps) {
134169 agentIdentifier = { agent . identifier }
135170 selectedIntegrationId = { selectedIntegrationId ?? defaultFromAgent ?. integrationId }
136171 linkedIntegrationIds = { linkedIntegrationIds }
137- onSelect = { ( _providerId , integration ) => {
138- if ( integration ?. _id ) {
139- setSelectedIntegrationId ( integration . _id ) ;
140- sessionStorage . setItem ( SESSION_KEY ( agent . identifier ) , integration . _id ) ;
141- }
142- } }
172+ onSelect = { handleProviderSelect }
143173 />
144174 }
145175 />
0 commit comments