# Troubles with Gibbs free energy

The book I'm reading writes that for a system at constant pressure and temperature it holds: $$dG=-TdS_{tot}$$ where $$dG=dH-TdS$$. So if you want to see if a certain process is spontaneus, you just have to look at the sign of $$dG$$, since it depends on the sign of $$dS_{tot}$$.
But I have a lot of doubts about this formula, indeed read the following scenario.
You consider a certain amount of liquid inside a piston at a fixed pressure given by the weight of the piston. Let's assume the liquid is changing its phase, so also its temperature stays constant at the value $$T$$. Out there is a heat reservoir at the temperature $$T_{res}$$, which touches the piston. Since the temperature can't be a discontinous function, you assume that there is a piece of metal which connects the reservoir and the piston. You have: $$dS_{tot}=dS_{res}+dS+dS_{metal}$$ If you consider a stationary transform, the state of the piece of metal doesn't change, then $$dS_{metal}=0$$. $$dS_{tot}=\frac{\delta Q}{T_{r}}-\frac{\delta Q}{T}$$ Since pressure is constant: $$dS_{tot}=dH[\frac{1}{T_{r}}-\frac{1}{T}]$$ Note that if $$T_{r}=T$$ then $$dS_{tot}=0$$ since there are no irreversibility in the universe (no finite differences of temperature), otherwise it must be $$dS_{tot}>0$$. I would stop at this point but let's introduce the Gibbs free energy.
Definig the Gibbs free energy as: $$G=H-TS$$ $$dG=dH-dTS-TdS$$ $$dH=dG+dTS+TdS$$ For constant temperature: $$dH=dG+TdS$$ You finally get: $$dS_{tot}=(dG+TdS)[\frac{1}{T_{r}}-\frac{1}{T}]$$ Which is not the same thing that writes my book. Also note that the temperature and the pressure of the system are constant, so I have the same hypothesis of the book but I get different results. Someone could clarify this? I'd really appreciate.

Your error occurs when you write that

$$dS_{tot}=\frac{\delta Q}{T_{r}}-\frac{\delta Q}{T}$$

since this assumes that

$$\delta Q=-TdS$$

which implies reversibility and therefore that $$dG=0$$ at constant T and p.

The more general statement is that

$$dS_{tot}=\frac{\delta Q}{T_{r}}+dS$$

which means that

$$dS_{tot}=-\frac{dH}{T_{r}}+dS$$

(since positive heat here means exothermic)

Then

$$T_{r}dS_{tot}=-dG+(T_{r}-T)dS$$

or

$$dG=-T_{r}dS_{tot}+(T_{r}-T)dS$$

Now if you let $$T=T_{r}$$ (thermal equilibrium with surroundings) then

$$dG=-TdS_{tot}$$