How can I prevent Mac terminal ssh from disconnecting when the screen is automatically turned off? I frequently use ssh on my MacBook to connect to other servers and run long-running commands there. When I do this, I leave the lid open to let it run, but then if I don't go to make coffee or something, it automatically turns the screen off, and this also causes the ssh to disconnect.

I tried to find how to prevent this automatically in the Terminal settings and in power saving settings, and couldn't find anything relevant. To prevent this disconnection I play a video silently, and this doesn't let power saving turn the screen off, but this is weird and lame to begin with, and if I forget to do this, then my session is lost. Is there anything better and more automatic?
As mentioned by Jakuje in the comments above, I strongly recommend using screen (or tmux) for long running commands or sessions that you would want to resume if disconnected for any reason.

Another approach would be to install mosh (https://mosh.org/) to make the connection. You can use it just like SSH and but it has support for intermittent connectivity (e.g., your laptop going to sleep) so that you can resume the connection without interruption from a user perspective.

However, I suspect your problem is not necessarily from the screen turning off, but from the SSH session timing out due to an idle connection.  You can edit your ~/.ssh/config file and add in an entry similar to the following

host your.remote.host
     ServerAliveInterval 180


which will cause your client to send a packet to the server every 180 seconds if it doesn't receive a packet from the server.