Components
In the ecosystem, components are what the end user actually touches — they expose AI tools and other functions as nodes on the Grasshopper canvas. End-user components live in src/SmartHopper.Components/, built on the base-class hierarchy in src/SmartHopper.Core/ComponentBase/.
See the Component Library for what ships; this page is about writing a new one.
Structure of a component
A component is a class with a stable contract, split across two pieces:
| Piece | What it is |
|---|---|
| The component class | Inherits a base (e.g. AIStatefulAsyncComponentBase). Overrides ComponentGuid (unique, stable forever — documents rehydrate through it), Exposure, Keywords, parameter registration, UsingAiTools, and CreateWorker. |
| The worker | AsyncWorkerBase subclass — the three-phase lifecycle GatherInput (UI thread) → DoWorkAsync (background) → SetOutput (UI thread). Covered below. |
The bases do the heavy lifting — state machine, async lifecycle, provider/model selection, Settings/Metrics plumbing, output persistence — so a component file mostly describes its parameters and what work to do per item.
Pick the right base class
| Base | Choose when |
|---|---|
AIStatefulAsyncComponentBase | The default for AI components — stateful run button, provider/model badge, Settings input, Metrics output, managed tool calls and batch mode. Most AI* components use it (often via the adapter subclasses). |
AIOutputAdapterBase | AI component shaped as Input > payload → typed outputs via OutputMappings (text2text, text2json, list ops). |
AIInputAdapterBase | Non-AI input component that emits an AIInputPayload (Input > output). Derives straight from GH_Component. |
AISelectingStatefulAsyncComponentBase | AI component that also needs the selection UI (pick objects on canvas). |
SelectingStatefulComponentBase | Non-AI component needing run-state + selection UI (e.g. GhGet-style tools). |
StatefulComponentBase | Non-AI long-running component with the Run toggle and persistence. |
AsyncComponentBase | Plain "do work off the UI thread" component — the root of the async chain. |
ProviderComponentBase, SelectingComponentBase | Non-stateful GH_Components that still need provider selection / selection UI without the full async+state stack. |
Anatomy of an AI component
Modeled on AIText2TextComponent (src/SmartHopper.Components/Text/). You typically override five things:
public class AIText2TextComponent : AIStatefulAsyncComponentBase
{
public override Guid ComponentGuid => new("EB073C7A-A500-4265-A45B-B1BFB38BA58E");
public override GH_Exposure Exposure => GH_Exposure.primary;
public override IEnumerable<string> Keywords => new[] { "AI", "text", "generate" };
// 1. Which tools this component needs — drives capability requirements,
// tool availability, and the managed request pipeline.
protected override IReadOnlyList<string> UsingAiTools => new[] { "text2text" };
// 2. Extra outputs beyond the built-ins (Settings/Run in, Metrics out).
protected override void RegisterAdditionalOutputParams(GH_OutputParamManager pManager)
{
pManager.AddTextParameter("Result", "R", "The AI's response", GH_ParamAccess.tree);
}
// … and RegisterAdditionalInputParams for your inputs (Prompt, Instructions…)
// 3. The worker — where the actual work happens, off the UI thread.
protected override AsyncWorkerBase CreateWorker(Action<string> progressReporter)
{
return new AIText2TextWorker(this, this.AddRuntimeMessage, this.ComponentProcessingOptions);
}
}
The worker: GatherInput → DoWorkAsync → SetOutput
AsyncWorkerBase is a three-phase background worker:
private sealed class AIText2TextWorker : AsyncWorkerBase
{
private Dictionary<string, GH_Structure<GH_String>> inputTree;
private Dictionary<string, GH_Structure<GH_String>> result;
// Phase 1 (UI thread): harvest inputs into plain data.
public override void GatherInput(IGH_DataAccess DA, out int dataCount)
{
var promptTree = new GH_Structure<GH_String>();
DA.GetDataTree("Prompt", out promptTree);
this.inputTree = new Dictionary<string, GH_Structure<GH_String>>
{
["Prompt"] = promptTree,
};
dataCount = 0;
}
// Phase 2 (background): do the work — NO Rhino/GH UI access here.
public override async Task DoWorkAsync(CancellationToken token)
{
this.result = await this.parent.RunProcessingAsync(
this.inputTree,
branches => ProcessData(branches, this.parent, token),
this.processingOptions,
token);
// Batch mode? Submit the collected queue instead of finishing inline.
if (!await this.parent.TrySubmitBatchAsync("Result", this.result, token))
{
this.parent.FinishResults("Result", this.result["Result"]); // persist + metrics
}
}
// Phase 3 (UI thread): outputs usually already persisted by FinishResults —
// RestorePersistentOutputs replays them on the next solve.
public override void SetOutput(IGH_DataAccess DA, out string message)
=> message = string.Empty;
}
Inside ProcessData, inputs arrive as Dictionary<string, List<T>> — already branched, no path handling needed:
private static async Task<Dictionary<string, List<GH_String>>> ProcessData(
Dictionary<string, List<GH_String>> branches, …, CancellationToken ct)
{
var prompts = branches["Prompt"];
var norm = DataTreeProcessor.NormalizeBranchLengths(new List<List<GH_String>> { prompts, instructions });
var outputs = new Dictionary<string, List<GH_String>> { ["Result"] = new() };
for (int i = 0; i < prompts.Count; i++)
{
var parameters = new JObject { ["prompt"] = norm[0][i]?.Value, ["contextFilter"] = "-*" };
var toolResult = await parent.CallAIToolAsync("text2text", parameters, ct);
outputs["Result"].Add(new GH_String(toolResult?["result"]?.ToString() ?? ""));
}
return outputs;
}
The pieces the base gives you
UsingAiTools— declare tools once; the base computes requiredAICapability, wires a managedConversationSession, and exposesCallAIToolAsync(name, params, ct)to the worker.RunProcessingAsync/ProcessData— the data-tree engine: gathers your inputs, fans out per branch, calls yourProcessDatacallback, reassembles output trees.FinishResults(name, tree)— the single funnel for outputs: persists viaGHPersistenceService, emits metrics, feeds theMetricsoutput. Batch mode'sProcessBatchResultsconverges here too.TrySubmitBatchAsync— when the provider supports batch, collect items instead of calling per item.RunOnlyOnInputChanges(onStatefulComponentBase, defaulttrue) —falsere-runs when the provider/model selection changes, which is usually what you want for AI components.- Provider/model badge &
Settingsinput — fromAIProviderComponentBase; persisted selections, capability-aware model filtering. ComponentProcessingOptions— the Settings-input parse (context filter, run policy) passed to the worker.
Hard rules
- Workers never touch UI.
DoWorkAsyncruns off-thread; any Rhino/GH UI call (canvas refresh, dialogs,Instances.ActiveCanvasreads that need the UI thread) must be marshalled back — the base marshals state/output for you; custom UI calls are on you. - One output funnel. Don't set outputs directly in
SetOutputfor AI components —FinishResults+RestorePersistentOutputsown persistence and metrics. - Errors →
CollectMessage(SHRuntimeMessageSeverity.Error, …)in the worker (orCreateErrorin tools) — actionable text, not stack dumps. - Undo for canvas mutations. Any component writing to the document registers undo records (
grasshopper-undo.mdrule). - Trees, not items. Inputs/outputs are
GH_Structure<T>— useDataTreeProcessor.NormalizeBranchLengthsand theProcessDatadictionary contract rather than manual path math (data-tree-processing.mdrule). ComponentGuidmust be unique and stable — it's how documents rehydrate your component. Generate once, never change.
Testing
No unit test may reference Rhino/Grasshopper. If a component's behavior genuinely needs the canvas, write a testing component in src/SmartHopper.Components.Test/ (excluded from Release, never shipped) — e.g. TestGhGetPutComponent, TestGhComponentLockComponent. Pure logic (tree math, payload shaping, request building) goes in SmartHopper.Core.Tests / Core.Grasshopper.Tests as normal unit tests.