Docs · Extensions

Extension Interfaces Reference#

All Verso extensions implement one or more interfaces from Verso.Abstractions. Each interface extends IExtension, which provides identity, versioning, and lifecycle hooks. Classes must be decorated with [VersoExtension] to be discovered by the host.

This document covers every extension interface, its required members, lifecycle behavior, and links to reference implementations.


IExtension#

The base interface for all extensions. Every extension class must implement this, and every capability interface (ILanguageKernel, ICellRenderer, etc.) extends it.

Members#

Member Type Description
ExtensionId string Unique identifier in reverse-domain format (e.g., "com.mycompany.myext").
Name string Human-readable display name.
Version string Semantic version string (e.g., "1.2.0").
Author string? Optional author or publisher name.
Description string? Optional short description of the extension. For a toolbar action or a notebook panel this doubles as the description of that button or panel: hosts show it beneath the name in the control's tooltip.
OnLoadedAsync(IExtensionHostContext) Task Called when the host loads the extension. Use for initialization and service registration.
OnUnloadedAsync() Task Called when the host unloads the extension. Use for cleanup.

Lifecycle#

  1. The host scans assemblies for [VersoExtension]-attributed classes.
  2. It instantiates each class and calls OnLoadedAsync, passing an IExtensionHostContext.
  3. The extension remains active until OnUnloadedAsync is called (e.g., on host shutdown or extension disable).

Example Implementation#

See the Dice sample: samples/extensions/Verso.Sample.Dice/DiceExtension.cs


ILanguageKernel#

Executes code, provides completions, diagnostics, and hover information for a specific language. Extends both IExtension and IAsyncDisposable.

Members (in addition to IExtension)#

Member Type Description
LanguageId string Language identifier used to associate cells with this kernel (e.g., "csharp", "python").
DisplayName string Human-readable language name shown in UI selectors.
FileExtensions IReadOnlyList<string> File extensions for this language (e.g., ".cs", ".py").
InitializeAsync() Task One-time initialization called before any execution.
ExecuteAsync(string, IExecutionContext) Task<IReadOnlyList<CellOutput>> Executes source code and returns outputs.
GetCompletionsAsync(string, int) Task<IReadOnlyList<Completion>> Returns completion suggestions at the cursor position.
GetDiagnosticsAsync(string) Task<IReadOnlyList<Diagnostic>> Analyzes code and returns diagnostics (errors, warnings).
GetHoverInfoAsync(string, int) Task<HoverInfo?> Returns type/doc info for the symbol at the cursor.
DisposeAsync() ValueTask Releases kernel runtime resources (from IAsyncDisposable).

Lifecycle#

  1. OnLoadedAsync -- host registers the kernel.
  2. InitializeAsync -- called once before first execution.
  3. ExecuteAsync / GetCompletionsAsync / GetDiagnosticsAsync / GetHoverInfoAsync -- called as needed during notebook use.
  4. DisposeAsync -- called on kernel restart or host shutdown.

Diagnostics in the Editor#

What GetDiagnosticsAsync returns is drawn in the cell editor as squiggles. The editor asks after the user pauses typing (about half a second), when the cell's editor gains focus, and after the cell runs. It does not ask while any cell in the notebook is running, and it clears every marker in the notebook when any kernel restarts. Diagnostics are advisory: if the kernel fails to initialize or GetDiagnosticsAsync throws, the request goes unanswered and the editor keeps the markers it already shows (none, for a kernel that never started); the failure is reported where it matters, when the cell runs. Return an empty list, not an exception, when there is nothing to report, so fixed problems are cleared.

Leading #! magic command lines are blanked before the code reaches the kernel, keeping the line count, so a kernel never has to recognize them and its positions still match the cell. At run time the pipeline removes those lines instead, so a kernel that reads a directive from the cell's first line (as SQL reads --connection) should skip leading blank lines when it looks for that line during diagnostics.

DiagnosticSeverity Shown as
Error Error squiggle
Warning Warning squiggle
Info Info squiggle
Hidden Not shown

Positions are 0-based and relative to the cell's source, for lines and columns alike. The editor converts them to its own 1-based positions and clamps them to the text, so a stale or out-of-range span cannot break it.

A span is a location in the cell. When a diagnostic is about a line or the whole cell rather than a place in it (no connection, no valid request), report an empty span that starts at column 0 of the line it concerns, or line 0 for the whole cell: new Diagnostic(severity, message, line, 0, line, 0). The editor marks that whole line. An empty span anywhere else is kept as a point, which is right for something like a missing ; at the end of a line.

Code is shown beside the message (for example CS0103), and the kernel's DisplayName is shown as the source.

Example Implementation#

  • Dice sample: samples/extensions/Verso.Sample.Dice/DiceExtension.cs
  • Built-in: CSharpKernel in the Verso project
[VersoExtension]
public sealed class DiceExtension : ILanguageKernel
{
    public string LanguageId => "dice";
    public string DisplayName => "Dice";
    public IReadOnlyList<string> FileExtensions => new[] { ".dice" };

    public Task<IReadOnlyList<CellOutput>> ExecuteAsync(string code, IExecutionContext context)
    {
        // Parse dice notation and return results
        var outputs = new List<CellOutput>();
        // ... parsing logic ...
        return Task.FromResult<IReadOnlyList<CellOutput>>(outputs);
    }

    // ... other members ...
}

ICellRenderer#

Renders the input (editor) and output (result) areas of a cell. Each renderer is associated with a specific cell type via CellTypeId.

Members (in addition to IExtension)#

Member Type Description
CellTypeId string Identifier of the cell type this renderer handles.
DisplayName string Human-readable name for this renderer.
CollapsesInputOnExecute bool Whether the input editor collapses after execution, showing only output. Defaults to false.
DefaultVisibility CellVisibilityHint Hint to layouts about the cell type's presentability. Default interface member, defaults to CellVisibilityHint.Content. See Layout Authoring for how layouts use this.
RenderInputAsync(string, ICellRenderContext) Task<RenderResult> Renders the cell's source code as visual content.
RenderOutputAsync(CellOutput, ICellRenderContext) Task<RenderResult> Renders a single execution output.
GetEditorLanguage() string? Returns the editor language ID for syntax highlighting, or null.

Lifecycle#

Renderers are stateless. RenderInputAsync and RenderOutputAsync are called whenever the UI needs to display or refresh a cell. Use ICellRenderContext to access theme colors, cell metadata, and dimensions.

Example Implementation#

  • Dice sample: samples/extensions/Verso.Sample.Dice/DiceRenderer.cs
  • Built-in: MarkdownRenderer
[VersoExtension]
public sealed class DiceRenderer : ICellRenderer
{
    public string CellTypeId => "dice";
    public string DisplayName => "Dice";

    public Task<RenderResult> RenderInputAsync(string source, ICellRenderContext context)
    {
        var html = $"<pre><code>{HttpUtility.HtmlEncode(source)}</code></pre>";
        return Task.FromResult(new RenderResult("text/html", html));
    }

    public Task<RenderResult> RenderOutputAsync(CellOutput output, ICellRenderContext context)
    {
        // Render output content
        return Task.FromResult(new RenderResult("text/html", output.Content));
    }

    public string? GetEditorLanguage() => null;
}

IDataFormatter#

Formats runtime objects into display outputs. The host selects the best formatter by checking SupportedTypes, Priority, and CanFormat.

Members (in addition to IExtension)#

Member Type Description
SupportedTypes IReadOnlyList<Type> CLR types this formatter handles. Used for fast pre-filtering.
Priority int Conflict resolution priority. Higher values win.
IsFallback bool Whether this is a generic fallback formatter. Defaults to false; kernels may skip fallbacks in favor of native runtime formatting.
CanFormat(object, IFormatterContext) bool Fine-grained check for whether this formatter can handle the value and emit the requested context.MimeType.
FormatAsync(object, IFormatterContext) Task<CellOutput> Produces a CellOutput for the given value.

Lifecycle#

Formatters are stateless and invoked on-demand. When a kernel produces an object result, the host filters registered formatters by SupportedTypes, probes CanFormat for the host's acceptable MIME types, and calls FormatAsync only for the winning formatter and representation. MIME preference takes precedence over formatter Priority; priority resolves conflicts within one MIME type.

CanFormat must return false when the formatter cannot emit context.MimeType. A formatter that claims a MIME type but returns a different one is skipped so the host never receives a representation it did not declare as renderable.

Generic catch-all formatters should return true from IsFallback. Explicit display operations include them, while language kernels can request only specialized formatters and retain their own native formatting when none matches.

Example Implementation#

  • Dice sample: samples/extensions/Verso.Sample.Dice/DiceFormatter.cs
  • Built-in: PrimitiveFormatter, CollectionFormatter, ExceptionFormatter, HtmlFormatter, SvgFormatter, ImageFormatter
[VersoExtension]
public sealed class DiceFormatter : IDataFormatter
{
    public IReadOnlyList<Type> SupportedTypes => new[] { typeof(DiceResult) };
    public int Priority => 10;

    public bool CanFormat(object value, IFormatterContext context)
        => context.MimeType.Equals("text/html", StringComparison.OrdinalIgnoreCase) &&
           value is DiceResult;

    public Task<CellOutput> FormatAsync(object value, IFormatterContext context)
    {
        var result = (DiceResult)value;
        var html = $"<table>...</table>"; // Build HTML table
        return Task.FromResult(new CellOutput("text/html", html));
    }
}

IToolbarAction#

Defines an action that appears on the notebook toolbar, cell toolbar, or context menu. Actions have enable/disable logic based on notebook state.

Members (in addition to IExtension)#

Member Type Description
ActionId string Unique identifier for this action (e.g., "dice.action.roll-all").
DisplayName string Label shown on the button or menu item.
Icon string? Optional icon name or path.
IconOnly bool When true, render only the icon with no text label. Default interface member, defaults to false. Set a Description alongside it: the icon is the only thing on screen, and the tooltip is the only place left to explain it.
IsPrimary bool Marks the action as primary so the toolbar can emphasize it. Default interface member, defaults to false.
ConfirmationPrompt string? When set, the host confirms with this message before running the action. Default interface member, defaults to null.
Placement ToolbarPlacement Where the action appears: MainToolbar, CellToolbar, ContextMenu, or ExportMenu.
Order int Sort order within its placement group. Lower values appear first.
IsEnabledAsync(IToolbarActionContext) Task<bool> Whether the action is currently enabled.
ExecuteAsync(IToolbarActionContext) Task Performs the action.

ToolbarPlacement Enum#

Value Description
MainToolbar Primary toolbar at the top of the notebook.
CellToolbar Inline toolbar within an individual cell.
ContextMenu Right-click context menu.
ExportMenu The Export dropdown in the main toolbar.

Lifecycle#

IsEnabledAsync is called when the UI refreshes (e.g., cell selection changes). ExecuteAsync is called when the user triggers the action.

Example Implementation#

  • Dice sample: samples/extensions/Verso.Sample.Dice/DiceRollAction.cs
  • Built-in: RunAllAction, RunCellAction, ClearOutputsAction, RestartKernelAction, ExportHtmlAction, ExportMarkdownAction, SwitchThemeAction
[VersoExtension]
public sealed class DiceRollAction : IToolbarAction
{
    public string ActionId => "dice.action.roll-all";
    public string DisplayName => "Roll All";
    public ToolbarPlacement Placement => ToolbarPlacement.MainToolbar;
    public int Order => 100;

    public Task<bool> IsEnabledAsync(IToolbarActionContext context)
    {
        var hasDiceCells = context.NotebookCells
            .Any(c => string.Equals(c.Language, "dice", StringComparison.OrdinalIgnoreCase));
        return Task.FromResult(hasDiceCells);
    }

    public async Task ExecuteAsync(IToolbarActionContext context)
    {
        foreach (var cell in context.NotebookCells.Where(c => c.Language == "dice"))
            await context.Notebook.ExecuteCellAsync(cell.Id);
    }
}

IMagicCommand#

Defines an inline directive invoked with a prefix such as %time or #!nuget. Magic commands extend kernel functionality without requiring a full UI component.

Members (in addition to IExtension)#

Member Type Description
Name string Command name used for invocation (e.g., "time", "nuget"). Shadows IExtension.Name.
Description string Short help text. Shadows IExtension.Description.
Parameters IReadOnlyList<ParameterDefinition> Parameter definitions for parsing and help generation.
ExecuteAsync(string, IMagicCommandContext) Task Executes the command with the raw argument string.

ParameterDefinition Record#

Property Type Description
Name string Parameter name as it appears in usage.
Description string Human-readable description.
ParameterType Type Expected CLR type for the value.
IsRequired bool Whether the parameter is mandatory. Default false.
DefaultValue object? Default when not supplied. Default null.

Lifecycle#

Magic commands are parsed from cell source code before kernel execution. The command's ExecuteAsync runs first. If context.SuppressExecution is set to true, normal kernel execution is skipped.

Example Implementation#

  • Built-in: TimeMagicCommand, NuGetMagicCommand, RestartMagicCommand, ImportMagicCommand

ICellType#

Defines a cell type by pairing a renderer with an optional language kernel. Cell types appear in the cell type picker.

Members (in addition to IExtension)#

Member Type Description
CellTypeId string Unique cell type identifier (e.g., "code-csharp", "markdown").
DisplayName string Label shown in the cell type picker.
Icon string? Optional icon for menus.
Renderer ICellRenderer The renderer for cells of this type.
Kernel ILanguageKernel? Optional kernel for executable cell types. null for non-executable types.
IsEditable bool Whether the cell content can be edited.
GetDefaultContent() string Default source inserted when a new cell of this type is created.

Lifecycle#

Cell types are registered at load time. The host uses CellTypeId to match cells to their renderer and kernel.


INotebookSerializer#

Serializes and deserializes notebooks to and from file formats. The host selects the serializer based on file extension.

Members (in addition to IExtension)#

Member Type Description
FormatId string Format identifier (e.g., "jupyter", "verso-native").
FileExtensions IReadOnlyList<string> File extensions handled (e.g., ".ipynb", ".vnb"), including the leading dot.
SerializeAsync(NotebookModel) Task<string> Converts a NotebookModel to its serialized string form.
DeserializeAsync(string) Task<NotebookModel> Parses serialized content into a NotebookModel.
CanImport(string) bool Checks if this serializer can import the file at the given path.
PreservesFormatByDefault bool Whether this format is auto-selected on save without an explicit opt-in setting or flag. Default interface member, defaults to false.

Lifecycle#

Serializers are stateless. DeserializeAsync is called when opening a file; SerializeAsync when saving.

Example Implementation#

  • Built-in: JupyterSerializer, VersoSerializer

ILayoutEngine#

Manages the spatial arrangement of cells. Layouts support different paradigms such as linear, grid, or freeform canvas.

Members (in addition to IExtension)#

Member Type Description
LayoutId string Layout identifier (e.g., "linear", "grid").
DisplayName string Name shown in the layout picker.
Icon string? Optional icon.
Capabilities LayoutCapabilities Flags declaring supported operations.
RequiresCustomRenderer bool Whether the layout needs a custom rendering surface.
RendererIsolation LayoutRendererIsolation Inline or Isolated: whether the layout renders inline in the host DOM or inside a sandboxed iframe. Default interface member, defaults to Inline.
GetRendererPackageAsync(IVersoContext) Task<LayoutRendererPackage?> For isolated layouts, returns the HTML/JS/CSS package served into the iframe. Default returns null.
GetStaticAssetsAsync(IVersoContext, LayoutHostCapabilities) Task<IReadOnlyList<LayoutStaticAsset>?> Static assets the host should serve for the layout. Default returns null.
RenderLayoutAsync(IReadOnlyList<CellModel>, IVersoContext) Task<RenderResult> Renders the full layout for all cells.
GetCellContainerAsync(Guid, IVersoContext) Task<CellContainerInfo> Returns position/bounds for a specific cell.
OnCellAddedAsync(Guid, int, IVersoContext) Task Notification that a cell was added.
OnCellRemovedAsync(Guid, IVersoContext) Task Notification that a cell was removed.
OnCellMovedAsync(Guid, int, IVersoContext) Task Notification that a cell was moved.
GetLayoutMetadata() Dictionary<string, object> Returns layout state for persistence.
ApplyLayoutMetadata(Dictionary<string, object>, IVersoContext) Task Restores layout state from persisted metadata.
SupportedVisibilityStates IReadOnlySet<CellVisibilityState> Visibility states this layout handles. Default interface member, defaults to { Visible }. The properties panel uses this to determine which options to show.
SupportsPropertiesPanel bool Whether the cell properties panel should be shown when this layout is active. Default interface member, defaults to false.

LayoutCapabilities Flags#

Flag Value Description
None 0 No capabilities.
CellInsert 1 Cells can be inserted.
CellDelete 2 Cells can be deleted.
CellReorder 4 Cells can be reordered.
CellEdit 8 Cell content is editable.
CellResize 16 Cells can be resized.
CellExecute 32 Cells can be executed.
MultiSelect 64 Multiple cells can be selected.
NotebookEvents 128 The layout receives notebook lifecycle events (cell add, remove, move).

Example Implementation#

  • Built-in: NotebookLayout, DashboardLayout, PresentationLayout

ILayoutInteractionHandler#

Handles interactions routed from a custom layout's rendered UI back to extension code, whether the layout renders inline or inside an isolated frame. A layout with interactive controls pairs its ILayoutEngine with an ILayoutInteractionHandler that shares the same ExtensionId and LayoutId.

Members (in addition to IExtension)#

Member Type Description
LayoutId string The layout this handler serves. Must match a registered ILayoutEngine.
OnLayoutInteractionAsync(LayoutInteractionContext) Task Handles an interaction the client dispatches from the layout (via the layout/interact method).

See the Layout Authoring Guide for the event-routing model and worked examples.


ILayoutLifecycleHandler#

Observes the mount and unmount of an isolated (iframe) layout renderer, so an extension can push initial state into the frame or clean up when it goes away. Like the interaction handler, it pairs with an ILayoutEngine by ExtensionId and LayoutId.

Members (in addition to IExtension)#

Member Type Description
LayoutId string The layout this handler serves.
OnRendererMountedAsync(LayoutRendererMountContext) Task<IReadOnlyDictionary<string, object>?> Called when the renderer frame mounts; may return initial state for the frame.
OnRendererUnmountedAsync(LayoutRendererUnmountContext) Task Called when the renderer frame unmounts.

See the Layout Authoring Guide for isolated-renderer details.


ITheme#

Defines a complete visual theme including colors, typography, spacing, and syntax highlighting.

Members (in addition to IExtension)#

Member Type Description
ThemeId string Theme identifier (e.g., "verso-dark").
DisplayName string Name shown in the theme picker.
ThemeKind ThemeKind Whether the theme is Light, Dark, or HighContrast.
Colors ThemeColorTokens Color tokens for backgrounds, foregrounds, borders, and accents.
Typography ThemeTypography Font families, sizes, and line heights.
Spacing ThemeSpacing Padding, margin, and gap tokens.
GetCustomToken(string) string? Retrieves a custom design token by key.
GetSyntaxColors() SyntaxColorMap Returns syntax highlighting color mappings.

Example Implementation#

  • Built-in: VersoDarkTheme, VersoLightTheme

INotebookPostProcessor#

Hooks into the serialization pipeline to transform notebooks after deserialization and before serialization. Useful for cell injection, metadata migration, or format upgrades.

Members (in addition to IExtension)#

Member Type Description
Priority int Execution order. Lower values run first.
CanProcess(string?, string) bool Whether this processor applies to the given file and format.
PostDeserializeAsync(NotebookModel, string?) Task<NotebookModel> Transforms the notebook after deserialization (on open).
PreSerializeAsync(NotebookModel, string?) Task<NotebookModel> Transforms the notebook before serialization (on save).

Lifecycle#

Post-processors are sorted by Priority (ascending). CanProcess is checked first; if true, the transform method is called. Multiple processors form a chain -- each receives the output of the previous.


ICellPropertyProvider#

Contributes configurable property sections to the cell properties panel. When a cell is selected in the UI, the host queries all registered providers and composes their sections into the properties sidebar.

Members (in addition to IExtension)#

Member Type Description
Order int Display order within the panel. Lower values appear first.
AppliesTo(CellModel, ICellRenderContext) bool Whether this provider contributes properties for the given cell.
GetPropertiesSectionAsync(CellModel, ICellRenderContext) Task<PropertySection> Returns the property section definition with current values.
OnPropertyChangedAsync(CellModel, string, object?, ICellRenderContext) Task Called when the user changes a property value. The provider validates and writes the change to cell metadata.

Lifecycle#

Providers are stateless. AppliesTo is called first as a filter. For providers that return true, GetPropertiesSectionAsync produces the section definition. OnPropertyChangedAsync fires when a field value changes in the UI.

Property values are stored in CellModel.Metadata under extension-namespaced keys (e.g., "verso:ui.layoutVisibility", "myext:color"). Each provider owns its own namespace.

Panel Composition#

  1. The front-end queries all registered ICellPropertyProvider instances via IExtensionHostContext.GetPropertyProviders().
  2. Filters by AppliesTo(cell, context).
  3. Calls GetPropertiesSectionAsync on matching providers.
  4. Sections are rendered in Order sequence.
  5. Field changes call OnPropertyChangedAsync on the owning provider.

The properties panel is only visible when the active layout's SupportsPropertiesPanel is true.

PropertySection and PropertyField#

public sealed record PropertySection(
    string Title,
    string? Description,
    IReadOnlyList<PropertyField> Fields);

public sealed record PropertyField(
    string Name,
    string DisplayName,
    PropertyFieldType FieldType,
    object? CurrentValue,
    string? Description = null,
    IReadOnlyList<PropertyFieldOption>? Options = null,
    bool IsReadOnly = false);

public sealed record PropertyFieldOption(
    string Value,
    string DisplayName);

PropertyFieldType Enum#

Value Description
Text Free-form text input.
Number Numeric input.
Toggle Boolean checkbox.
Select Single-selection dropdown. Requires Options.
MultiSelect Multi-selection checkboxes. Requires Options.
Color Color picker.
Tags Tag list with comma/Enter to add.

Built-in Provider: CellVisibilityPropertyProvider#

Verso ships a built-in CellVisibilityPropertyProvider (ExtensionId: "verso.propertyprovider.visibility") that renders a Select field for each layout that supports more than just Visible in its SupportedVisibilityStates. Values are stored under the "verso:ui.layoutVisibility" metadata key. The legacy "verso:visibility" key is migrated automatically at notebook open time; support for the legacy key will be removed in a future release.

Example Implementation#

[VersoExtension]
public sealed class SqlPropertyProvider : ICellPropertyProvider
{
    public string ExtensionId => "com.mycompany.sql-properties";
    public string Name => "SQL Properties";
    public string Version => "1.0.0";
    public string? Author => "Your Name";
    public string? Description => "Connection and timeout settings for SQL cells.";

    public int Order => 10;

    public bool AppliesTo(CellModel cell, ICellRenderContext context)
        => string.Equals(cell.Type, "code", StringComparison.OrdinalIgnoreCase)
        && string.Equals(cell.Language, "sql", StringComparison.OrdinalIgnoreCase);

    public Task<PropertySection> GetPropertiesSectionAsync(CellModel cell, ICellRenderContext context)
    {
        var timeout = cell.Metadata.TryGetValue("myext:timeout", out var t) ? t : 30;
        var fields = new List<PropertyField>
        {
            new("timeout", "Query Timeout", PropertyFieldType.Number, timeout,
                Description: "Timeout in seconds")
        };
        return Task.FromResult(new PropertySection("SQL Settings", null, fields));
    }

    public Task OnPropertyChangedAsync(
        CellModel cell, string propertyName, object? value, ICellRenderContext context)
    {
        cell.Metadata[$"myext:{propertyName}"] = value!;
        return Task.CompletedTask;
    }

    public Task OnLoadedAsync(IExtensionHostContext context) => Task.CompletedTask;
    public Task OnUnloadedAsync() => Task.CompletedTask;
}

INotebookPanel#

Contributes a panel to the notebook UI, shown alongside the notebook body and toggled from the host's panel controls. Use this for information or actions that belong next to the notebook rather than inside a cell.

A panel's identity is the (ExtensionId, PanelId) pair, so two extensions may use the same PanelId without colliding. One extension declaring the same PanelId twice fails to load.

See Panels for the full authoring guide.

Members (in addition to IExtension)#

Member Type Description
PanelId string Identifier, unique within the owning extension.
DisplayName string Panel title and accessible name of its toggle.
IconName string? Name from the host's icon set. Hosts map it to their own glyphs.
IconMarkup string? Optional host-specific markup used in place of IconName by hosts that understand it. Defaults to null.
Order int Sort order among the panel controls. Lower values first. Built-in panels occupy 100 through 500.
IsAvailableAsync(IPanelContext) Task<bool> Whether the panel should be offered at all. A panel that returns false is omitted and closed if open.
RenderAsync(IPanelContext) Task<IReadOnlyList<RenderResult>> The panel's content as representations, richest first.

Representations#

RenderAsync returns the same content in one or more forms, ordered from richest to simplest. Each host renders the first entry whose MimeType it supports and ignores the rest.

public Task<IReadOnlyList<RenderResult>> RenderAsync(IPanelContext context)
{
    IReadOnlyList<RenderResult> representations = new[]
    {
        new RenderResult("text/html", BuildHtml(context)),
        new RenderResult("text/plain", BuildText(context))
    };
    return Task.FromResult(representations);
}

No host is obliged to support any particular media type. A panel that offers only text/html is simply unavailable on a host that does not render HTML, which is why offering a plain-text alternative is worth the few lines.

Icon Names#

Hosts are expected to recognize document, list, puzzle, braces, gear, search, layout, compare, info, warning, flag, check, clock, tag, chart, table, folder, and link. A name a host does not recognize falls back to IconMarkup, then to the first letter of DisplayName. An unrecognized name is not an error.

Lifecycle#

IsAvailableAsync is called when the host builds its panel list, which happens on notebook load and whenever the layout or the set of loaded extensions changes. It is not re-evaluated on every cell selection, so a panel whose content depends on the selection should stay available and read IPanelContext.SelectedCellId in RenderAsync, which the host does call on selection change.

IPanelContext#

Extends IVersoContext with the notebook state a panel is most likely to need.

Member Type Description
SelectedCellId Guid? Currently selected cell, or null when none is.
NotebookCells IReadOnlyList<CellModel> Ordered cells in the notebook.

A panel has no cell to write to, so WriteOutputAsync and UpdateOutputAsync throw. A panel that wants to affect the notebook goes through IVersoContext.Notebook, the same route a toolbar action takes.


IPanelInteractionHandler#

Handles actions the user triggers in a panel. Implement alongside INotebookPanel on the same class (the common case) or as a sibling class sharing the same PanelId. Routing is by the (ExtensionId, PanelId) pair, and a handler whose extension registers no panel with that id fails to load.

Members (in addition to IExtension)#

Member Type Description
PanelId string The panel this handler services.
OnPanelInteractionAsync(PanelInteractionContext) Task Called when the host reports a triggered action.

PanelInteractionContext#

Property Type Description
ExtensionId string Owning extension.
PanelId string Panel the action targets.
InteractionType string Application-defined action name (e.g. "accept").
Payload string Free-form payload from the host.
TargetId string? Which item within the panel the action applies to.
SelectedCellId Guid? Cell selected when the action was triggered.
Verso IVersoContext Variables, theme, notebook operations, extension host.
RequestRefresh Action Asks the host to discard the panel's content and request it again.

Nothing in this context names a rendering technology. How a host detects that an action was triggered is the host's business and varies by host.

Interaction types in the verso/ namespace are reserved by the host and are intercepted before the handler runs, so using that prefix as an application-defined type will silently never reach your handler.


Augmentation Interfaces#

These interfaces are not standalone extension capabilities. They are implemented alongside a primary capability interface (e.g., ILanguageKernel + IExtensionSettings or IDataFormatter + ICellInteractionHandler). They do not extend IExtension and cannot be the sole interface on a [VersoExtension] class.

IExtensionSettings#

Exposes configurable settings for an extension. The host persists setting overrides in the .verso file and renders a settings UI.

Member Type Description
SettingDefinitions IReadOnlyList<SettingDefinition> Static list of setting definitions declared by this extension.
GetSettingValues() IReadOnlyDictionary<string, object?> Returns current values of all settings (or only those differing from defaults).
ApplySettingsAsync(IReadOnlyDictionary<string, object?>) Task Batch-restores settings from persisted values (e.g., when opening a file). Unknown names should be silently ignored.
OnSettingChangedAsync(string, object?) Task Called when a single setting is changed interactively from the UI.

SettingDefinition Record#

Property Type Description
Name string Programmatic setting name (e.g., "warningLevel").
DisplayName string Human-readable label shown in the settings UI.
Description string Longer description of what the setting controls.
SettingType SettingType Data type of the value (see enum below).
DefaultValue object? Default when no override is persisted. Default null.
Category string? Optional grouping category (e.g., "Compiler", "Editor"). Default null.
Constraints SettingConstraints? Optional validation constraints. Default null.
Order int Display order within category. Lower values appear first. Default 0.

SettingType Enum#

Value Description
String Free-form text value.
Integer Whole number (System.Int32).
Double Floating-point number (System.Double).
Boolean True/false value.
StringChoice String restricted to a fixed set of choices (see SettingConstraints.Choices).
StringList Ordered list of string values.

SettingConstraints Record#

Property Type Description
MinValue double? Minimum numeric value (inclusive). Applies to Integer and Double.
MaxValue double? Maximum numeric value (inclusive). Applies to Integer and Double.
Pattern string? Regex pattern the value must match. Applies to String.
Choices IReadOnlyList<string>? Allowed values. Applies to StringChoice.
MaxLength int? Maximum string length. Applies to String.
MaxItems int? Maximum number of items. Applies to StringList.

Example Usage#

[VersoExtension]
public sealed class MyKernel : ILanguageKernel, IExtensionSettings
{
    private int _warningLevel = 3;

    public IReadOnlyList<SettingDefinition> SettingDefinitions => new[]
    {
        new SettingDefinition(
            "warningLevel", "Warning Level", "Compiler warning level (0-4).",
            SettingType.Integer, DefaultValue: 3,
            Constraints: new SettingConstraints(MinValue: 0, MaxValue: 4))
    };

    public IReadOnlyDictionary<string, object?> GetSettingValues()
        => new Dictionary<string, object?> { ["warningLevel"] = _warningLevel };

    public Task ApplySettingsAsync(IReadOnlyDictionary<string, object?> values)
    {
        if (values.TryGetValue("warningLevel", out var val) && val is int level)
            _warningLevel = level;
        return Task.CompletedTask;
    }

    public Task OnSettingChangedAsync(string name, object? value)
        => ApplySettingsAsync(new Dictionary<string, object?> { [name] = value });

    // ... ILanguageKernel members ...
}

ICellInteractionHandler#

Handles bidirectional interactions from rendered cell content. Implement alongside a formatter or renderer to support interactive outputs (e.g., paginated tables, inline forms, drill-down panels).

Member Type Description
OnCellInteractionAsync(CellInteractionContext) Task<string?> Handles an interaction event. Returns an optional response string to send back to the client, or null.

CellInteractionContext#

Property Type Description
Region CellRegion Which cell region originated the interaction (Input or Output).
InteractionType string Application-defined type (e.g., "click", "paginate", "submit").
Payload string Free-form payload from the client (e.g., JSON, form data, page number).
OutputBlockId string? Optional identifier of the output block to update in place.
CellId Guid The cell where the interaction occurred.
ExtensionId string The extension identifier of the handler that should process this interaction.
CancellationToken CancellationToken Cancellation token for the operation.

Example Usage#

[VersoExtension]
public sealed class MyFormatter : IDataFormatter, ICellInteractionHandler
{
    // IDataFormatter members ...

    public async Task<string?> OnCellInteractionAsync(CellInteractionContext context)
    {
        if (context.InteractionType == "paginate")
        {
            var page = int.Parse(context.Payload);
            var html = RenderPage(page);
            return html; // Sent back to the client
        }
        return null;
    }
}

Key Models#

These records and classes are shared across all interfaces:

Model Description
CellOutput(MimeType, Content, IsError, ErrorName, ErrorStackTrace) Output produced by cell execution.
RenderResult(MimeType, Content) Rendered content returned by renderers.
Completion(DisplayText, InsertText, Kind, Description, SortText) Code completion item.
Diagnostic(Severity, Message, StartLine, StartColumn, EndLine, EndColumn, Code) Code diagnostic. Severity is a DiagnosticSeverity enum: Hidden, Info, Warning, Error.
HoverInfo(Content, MimeType, Range) Hover tooltip. MimeType defaults to "text/plain". Range is an optional (int StartLine, int StartColumn, int EndLine, int EndColumn)? tuple (zero-based).
ParameterDefinition(Name, Description, ParameterType, IsRequired, DefaultValue) Magic command parameter definition.
VariableDescriptor(Name, Value, Type, KernelId) Describes a stored variable.
CellContainerInfo Cell layout position returned by ILayoutEngine.GetCellContainerAsync. Properties: CellId, X, Y, Width, Height, IsVisible.
ExtensionInfo(ExtensionId, Name, Version, Author, Description, Status, Capabilities) Metadata for a loaded extension, returned by IExtensionHostContext.GetExtensionInfos().
ExtensionConsentInfo(PackageId, Version, Source) Describes a package pending user consent, used by IExtensionHostContext.RequestExtensionConsentAsync().
FontDescriptor(Family, SizePx, Weight, LineHeight) Font specification used by ThemeTypography. Weight defaults to 400, LineHeight defaults to 1.4.
VariableExplorerEntry(Name, TypeName, ValuePreview, IsExpandable) Display entry for the variable explorer panel.
SyntaxColorMap Mutable map used by ITheme.GetSyntaxColors(). Methods: Set(string, string), Get(string), GetAll(), Count.
PropertySection(Title, Description, Fields) Section heading and field list for the cell properties panel.
PropertyField(Name, DisplayName, FieldType, CurrentValue, Description, Options, IsReadOnly) Individual property field definition.
PropertyFieldOption(Value, DisplayName) Option for Select and MultiSelect fields.

CellModel#

Mutable model representing a single cell. Serialized properties:

Property Type Description
Id Guid Unique cell identifier. Auto-generated on creation.
Type string Cell type (e.g., "code", "markdown"). Default "code".
Language string? Language identifier, or null if unspecified.
Source string Source text content. Default "".
Outputs List<CellOutput> Outputs from execution.
Metadata Dictionary<string, object> Arbitrary key-value metadata.

Transient properties (not serialized, [JsonIgnore]):

Property Type Description
ExecutionCount int? Session-scoped execution counter, or null if not yet executed.
LastElapsed TimeSpan? Wall-clock duration of the most recent execution.
LastStatus string? "Success", "Failed", or "Cancelled".

NotebookModel#

Mutable model representing a full notebook document.

Property Type Default Description
FormatVersion string "1.0" Notebook file format version.
Title string? null Display title.
Created DateTimeOffset? null Creation timestamp.
Modified DateTimeOffset? null Last-modified timestamp.
DefaultKernelId string? null Default kernel for new code cells.
ActiveLayoutId string? null Currently active layout.
PreferredThemeId string? null Preferred theme.
RequiredExtensions List<string> [] Extensions that must be loaded for this notebook to function.
OptionalExtensions List<string> [] Extensions that may enhance the notebook but are not required.
Cells List<CellModel> [] Ordered list of cells.
Layouts Dictionary<string, object> {} Named layout definitions.
ExtensionSettings Dictionary<string, Dictionary<string, object?>> {} Per-extension settings keyed by extension ID. Only overrides are persisted.

See Also#