How to enable undo for operators in sculpt mode? I wrote a operator like that, And when I run this from object mode, everything is fine but if I run from sculpt mode, it cleans all the undo history and I ain't able to undo anything I did before.
Why is that?
class MaskDecimate(bpy.types.Operator):
    bl_idname = &quot;flow_tools.decimate&quot;
    bl_label = &quot;Mask Decimate&quot;
    bl_description = &quot;&quot;
    bl_options = {&quot;REGISTER&quot;, &quot;UNDO&quot;}
    
    invoked = False
    
    ratio = bpy.props.FloatProperty(
        name=&quot;Ratio&quot;,
        description=&quot;How much to recuce&quot;,
        default=0.5,
        min = 0.0000001,
        max = 1.0
    )
    
    @classmethod
    def poll(cls, context):
        if context.active_object:
            if not context.active_object.mode == &quot;EDIT&quot;:
                return context.active_object.type == &quot;MESH&quot;
    
    
    def invoke(self, context, event):
        self.bm = bmesh.new()
        self.bm.from_mesh(context.active_object.data)
        wm = context.window_manager
        return wm.invoke_props_dialog(self)

    
    def execute(self, context):
        
        ob = context.active_object
        bm = self.bm
        bm.to_mesh(ob.data)
        
        layer = bm.verts.layers.paint_mask.verify()
        vg = ob.vertex_groups.new(name = &quot;paint_vertex_group_mask&quot;)
        vg.add([v.index for v in bm.verts], 1.0, &quot;REPLACE&quot;)
        
        for vert in bm.verts:
            mask_val = vert[layer]
            vg.add([vert.index], 1 - mask_val, &quot;REPLACE&quot;)
        
        md = ob.modifiers.new(type=&quot;DECIMATE&quot;, name=&quot;Decmater&quot;)
        md.ratio = self.ratio
        md.vertex_group = vg.name
        bpy.ops.object.modifier_apply(modifier=md.name)
        
        bm = bmesh.new()
        bm.from_mesh(ob.data)
        layer = bm.verts.layers.paint_mask.verify()
        
        for vert in bm.verts:
            vert[layer] = 1 - vg.weight(vert.index)
        
        ob.vertex_groups.remove(vg)
        
        bm.to_mesh(ob.data)
        bm.free()
        return {&quot;FINISHED&quot;}
As a variant of a solution. I could suggest adding history before all the code. But I'm pretty sure this is a bug in Blender's sculpt mode.
if context.mode != 'OBJECT':    
    bpy.ops.ed.undo_push()