undo a command (scripting)

 From:  pressure (PEER)
10939.1 
I’ve been having problems with undoing custom commands. Hoping that someone can shed some light on how to change these commands so that undoing them works better.

If I have something selected, run this:

code:
    var factory = moi.command.createFactory( 'line' );
    factory.setInput( 0, moi.vectorMath.createPoint( 0, 0, 0 ) );
    factory.setInput( 1, moi.vectorMath.createPoint( 0, 0, 10 ) );
    var lineInList = factory.calculate();
    
    moi.geometryDatabase.deselectAll();
    
    moi.geometryDatabase.addObjects(lineInList);


and then hit Undo, the new line goes away, but the previously selected object stays unselected.

But, if I swap the order of the last two lines:

code:
    var factory = moi.command.createFactory( 'line' );
    factory.setInput( 0, moi.vectorMath.createPoint( 0, 0, 0 ) );
    factory.setInput( 1, moi.vectorMath.createPoint( 0, 0, 10 ) );
    var lineInList = factory.calculate();
    
    moi.geometryDatabase.addObjects(lineInList);
    
    moi.geometryDatabase.deselectAll();


Then hitting Undo once causes the previously selected object to become selected again, while hitting Undo a second time makes the line finally go away.

How should I get a command to act like a single thing (1 undo unit generated ?) so that hitting Undo once brings back the scene exactly as it was before running the command?

EDITED: 4 Jan 2023 by PEER