in the first case, the planet tugs on the spacecraft and the spacecraft tugs on the planet in such a way that the planet winds up gaining a little bit of speed with respect to the Sun, becoming slightly more loosely bound, while the spacecraft loses quite a bit of speed (thanks to its much smaller mass), and becomes more tightly bound: transferring to a lower-energy orbit. The second case works the opposite way: the planet loses a little speed and becomes more tightly bound, while the spacecraft gains quite a lot of speed and transfers to a higher-energy orbit.