How does Command Z work through computer commands?
You should really try to implement this yourself, and then it will become quite obvious.
You define a stack where you put all the operations that the user performs.  Here are some examples:

Close window
Move file from one directory to another
Create file
Move icon on Desktop from $(x_1,y_1)$ to $(x_2, y_2)$
Type a character
Delete a character
Copy to clipboard

All of these operations have reasonable &quot;inverse&quot; operations.:

Close window → Reopen window
Move file from A to B → Move it back to A
Create file X → Delete file X
Move icon from pos1 to pos2 → Move it back to pos1
Type a character → Delete the previous typed character, etc.

When the stack contains &quot;reversable&quot; operations, the undo command simply pops the last operation off the stack and performs its inverse operation.
Some operations are not reversable, though, such as posting on the Internet, and permanently deleting a file.