Remove Conduit Display When Py Component is Disabled or File Switch/Close

I had a Python script to control display.conduit in Rhino, using an input toggle to switch the display on or off in the viewport. This works as expected when the component is enabled.

However, when I disable the Python component in the Grasshopper canvas, the conduit display remains visible in the viewport. In other words, the drawing stays on the screen even though the component is no longer active - the same issue occurs when toggling or closing the Grasshopper file.

My question is: how can I ensure that the conduit is also removed from the viewport when the component is disabled (also when switch/close GH file)?

py_ds.conduit_2.gh (6.3 KB)

Input toggle = True:

Input toggle = False:

Component = disable (Red-box still showing):

import Rhino
import Rhino.Geometry as rg
import Rhino.Display as rd
import scriptcontext as sc
import System.Drawing

# ✅ Switch to Rhino document
sc.doc = Rhino.RhinoDoc.ActiveDoc

# ✅ Create a test planar surface
origin = rg.Point3d(0, 0, 0)
plane = rg.Plane(origin, rg.Vector3d.ZAxis)
rect = rg.Rectangle3d(plane, x, 60)
crv = rect.ToNurbsCurve()
breps = rg.Brep.CreatePlanarBreps(crv)
surface = breps[0].Faces[0] if breps else None

# ✅ Define Conduit class
class SurfaceConduit(rd.DisplayConduit):
    def __init__(self, surface):
        self.surface = surface
        self.color = System.Drawing.Color.Red

    def DrawForeground(self, e):
        if self.surface:
            e.Display.DrawSurface(self.surface, self.color, 1)

# ✅ Sticky key identifier
key = "preview_conduit"

# ✅ Toggle display (controlled by toggle_input)
if surface:
    # toggle_input is a boolean input from Grasshopper
    if toggle_input:
        # If conduit has not been created yet, create and enable it
        if not sc.sticky.has_key(key):
            conduit = SurfaceConduit(surface)
            sc.sticky[key] = conduit
            conduit.Enabled = True
        else:
            # If conduit already exists, just update the surface
            conduit = sc.sticky[key]
            conduit.surface = surface
            conduit.Enabled = True
    else:
        # Disable and remove conduit
        if sc.sticky.has_key(key):
            conduit = sc.sticky[key]
            conduit.Enabled = False
            del sc.sticky[key]

# ✅ Force view redraw
sc.doc.Views.Redraw()

# ✅ Switch back to GH document
sc.doc = ghdoc