You didn’t indicate any error message like a “broken pipe” where the server is closing the connection due to inactivity and it always happens when disconnected from mains power and while idle (no activity) on your part. This is indicative of you Mac going into a power saving mode disconnecting the network connections.
Check your Battery settings
Check Low Power Mode; set it to “Never” to ensure your Mac doesn’t go into power saving mode when there’s no activity. You’ll also want to have your computer wake for network activity “Always” rather than the default if “on Power Adapter” (Battery → Options Button)
Modify your ssh config
Edit the ~/.ssh/config file (create if necessary) to set a low value interval:
This will send a “proof of life” signal every two minutes (120 seconds) to the server. You may want to tweak this if it still disconnects.
Keep the session alive on the server (preferred)
My preferred method is to use
screen to keep whatever session you’re running on the server alive in the event of a disconnect.
screen is usually included with macOS or Linux, but my preference is
tmux. Either of these would be installed on the server and not the client.
I (personally) don’t recommend caffeinate or similar methods to override power saving algorithms. Instead, I will use
tmux because it gives me a higher degree of safety in the event of a disconnect I have no control over like the Internet going down.
tmux will keep my session alive on the server which is what matters most