I started writing a package to do this once, ~15 years ago. Never finished. You can store window layout configurations to a register with C-x r w and restore with C-x r j, so the primitives are there.https://twitter.com/shapr/status/1153023944250802176 …
and then my callback was going to store the old config on a stack (wasn't going to use the standard undo stack, but my own). Godspeed, and please ping me if you get this working!