When user-space hits a key the keyboard driver activates a wakeup-source. This has the effect of causing the suspend request to abort (yes, this can be done race-free). The CPU says awake, the keystroke is responded to, userspace notices that the user is doing something and arranges not to go to sleep just yet (user may still throw phone out the window, but it is probably because they hit the wrong key by mistake).
And as for "do the necessary work": Please see https://lwn.net/Articles/464144/. Just as soon as I can get my new phone suspending reliably I'll be testing this is a real-life situation.