There are commands to know if you are in menu mode (inventory, map, spells...), but I can't find any command for exiting that mode, neither to change from one of the submodes to another.
Is there a command I'm not aware of, or a trick letting you exit menu mode?
I tested it adding a script to an NPC and placing the instructions in an onitemadded event, with a removeallitems before. When accessed the NPC inventory, giving an item didn't exit the menu but when I exit the menu manually all the items on the NPC are removed (so, the block executes).
In some of the multiple tests though, selecting the NPC name in the inventory menu exited the menu after the item addition, which may be because of the bug sending you out of inventory sometimes, or because of the block executing some of the times you change the inventory tab.
This seem to be similar to what happens with AI packages if you didn't use evaluatepackage instructions, but instead of a long waiting, the price seem to be the block not executing.