Attitudes towards Afghan refugees have ebbed and flowed with the security and political situation in Afghanistan, as well as domestic political and economic considerations.
While economic sanctions against Iran once led the country to attempt to relieve unemployment by forcibly returning Afghans to Afghanistan, it soon became clear that Afghans had carved out crucial niches in many sectors of the Iranian economy. Subsequent sanctions relief allowed Iran's new government to be more welcoming of Afghans in the country, ceasing repatriation operations and formalizing their presence via a comprehensive census.
On the other hand, Pakistan's fraught relationship with Afghanistan, with both sides accusing the other of attempting to destabilize their country, has led Pakistan to take a much more hard-line approach to Afghan refugees. The U.S. withdrawal and the "official" end of the war in Afghanistan has given Pakistan the political cover to begin returning Afghan refugees to a country that is by no means "safe" in reality.
For more on repatriation of Afghan refugees from Iran, see here
For more on repatriation of Afghan refugees from Pakistan, see here