Having foreign thoughts are no reason to grow upset.
Even when they come to a person while he is serving God–learning Torah or praying–there is no need to see them as a sign of failure.
Instead, they indicate that he has been growing spiritually and therefore has elicited a negative reaction from his animal soul.
Now that he has progressed, he must attain a new equilibrium (of freedom and choice).
–Rabbi Adin Steinsaltz