I do something very similar. With some hacky string matching you can detect wether a window is available for reception and get past that.
I desire a more robust system which injects the events into the harness directly, but haven't found a way that works across systems.
https://github.com/tcdent/dotfiles/blob/main/bin/agent-messa...