Python SDK

Every effect, event and UI component, with signatures.

Generated Tracks the alpha branch, so it can be ahead of the release you have installed.

On this page

The Python SDK and local app runtime are part of stable v1. MCP client APIs listed below are beta-gated; do not rely on them from a stable channel.

Overview

Plexi Python SDK.

Apps expose module-level init(size, args), update(event), and view() functions. The PluginRuntime drives the event loop: host sends JSON events on stdin, app responds with effects and component trees on stdout.

Python apps are sandboxed. They run through the CPython-in-WASM adapter (src/host/wasm_python.rs) inside their own wasmtime::Store with isolated linear memory — the same component boundary a Rust WASM app gets, not a native subprocess. An app reaches only the host interfaces Plexi links for its world, and protected effects (file, network, AI, clipboard, pane, audio, GPU) each require an explicit capability grant the user approves on first request. There is no ambient process access to escape to. See docs/wasm-runtime.md § Security Model for the full boundary.

Effects

SetState

SetState(data: dict, scope: str | None = None)

Merge data into in-memory state. scope selects which declared state scope receives the keys; None means the app’s default scope (the first entry of the manifest’s [state] scopes). Using a scope the app did not declare raises at apply time — never a silent fallback.

PersistState

PersistState(data: dict, scope: str | None = None)

Merge data into a scope’s state and persist that scope’s snapshot to disk. The host owns path construction: global state lives in ~/.plexi/app_states/, context state in <context_root>/.plexi/app_states/ — resolved against the pane’s context root at call time. scope=None targets the default scope.

Read-back rule (disk wins): the host checks the file before writing. A persist that loses to a concurrent external write is dropped — the host reloads the on-disk state instead and answers with an events.StateChanged, so re-apply your change from that event rather than assuming the persist landed. Writes are atomic (temp + rename) in both directions; a reader never sees a partial file.

SetSchedulerMode

SetSchedulerMode(mode: str, fps: int | None = None)

FileRead

FileRead(path: str)

Read a workspace file; the reply is an events.FileReadResult whose content is the file’s exact bytes (binary-safe). Decode yourself for text. Requires the fs.read capability.

FileWrite

FileWrite(path: str, content: bytes)

Write content bytes to a workspace file, binary-exact. Requires the fs.write capability. Reply is an events.FileWriteResult.

read_bytes(path: str)

Binary-exact file read. The reply’s FileReadResult.content holds the file’s exact bytes — WAV, PNG, any media round-trips unchanged.

write_bytes(path: str, content: bytes | bytearray)

Binary-exact file write. Rejects non-bytes payloads and payloads over MAX_FILE_IO_BYTES immediately, before the host round trip.

ReadPermissionDecisions

ReadPermissionDecisions()

Ask the host for the live permission-monitor inventory.

The host replies with :class:events.PermissionInventory. Only the bundled Permissions plugin receives entries; any other plugin gets an empty list with status="rejected".

PermissionDecision

PermissionDecision(id: str, action: str)

Change one live permission row.

action is revoke, reset, or allow. Only the bundled Permissions plugin may send it, and it is never a human decision: revoke applies, while allow and reset file a Needs you item that a person confirms in the host (status="needs_you"). Other plugins get status="rejected". The host replies with a fresh :class:events.PermissionInventory.

ReadHostLog

ReadHostLog(max_bytes: int = 256 * 1024)

Request the tail of the Plexi host channel log (logs.read capability).

The host owns path resolution — it tails its own ~/.plexi-<channel>/plexi.log and replies with an events.HostLogResult. The app never names or opens the file, so the request carries only how many trailing bytes to read.

OpenFilePicker

OpenFilePicker(request_id: str, filter: list[str] = list(), multiple: bool = False, mode: str = 'open')

Show a host file picker (fs.pick capability).

mode is "open" (existing file, or several when multiple is true), "folder" (directory; the grant covers the subtree), or "save" (destination that may not exist yet). filter lists file extensions without leading dots; empty accepts all files.

The host replies with :class:events.FilePicked — whose paths are already registered as scoped fs grants, so they can be passed verbatim to :class:FileRead / :class:FileWrite — or :class:events.FilePickCancelled (user dismissed, or capability denied).

HttpFetch

HttpFetch(url: str, method: str = 'GET', headers: dict = dict(), body: Optional[bytes] = None, params: Optional[dict[str, Any]] = None, tag: Optional[str] = None, request_id: Optional[str] = None)

McpConnect

McpConnect(request_id: str, server_id: str)

Open a connection to an MCP server the user configured (stint 0382).

server_id names a [servers.<id>] entry in the user’s mcp_servers.toml. The host resolves it to a command and owns the resulting process; the app never supplies argv. Requires the mcp.client capability. Answered by :class:events.McpConnected.

McpSend

McpSend(server_id: str, message: dict)

Send one JSON-RPC message to a connected MCP server.

message is a JSON-RPC object; the SDK serializes it. The transport is line-delimited, so the serialized form must not contain a newline — the host rejects one rather than splitting the message. Replies arrive asynchronously as :class:events.McpMessage, correlated by the app through the JSON-RPC id it chose.

McpDisconnect

McpDisconnect(server_id: str)

Close a connection and kill the server process. Answered by :class:events.McpClosed.

CliOperation

CliOperation(request_id: str, operation_id: str, values: dict = dict())

Request one typed command-line operation the app package declares in [[cli_operation]] (requires the cli.operations capability and the cli_operations experiment).

The app names an operation_id and supplies typed values for the slots that operation declares. It never supplies an executable, argument list, environment, working directory or shell text: the host rejects a request that carries anything else. The person approves each operation in the host’s approval surface, which states that the program runs with their account’s full authority and is not confined.

Answered by :class:events.CliOperationResult carrying the same request_id. The request may wait for a decision, so it can be outstanding for a while; use :class:CliOperationCancel to withdraw it.

CliOperationCancel

CliOperationCancel(request_id: str)

Withdraw an outstanding :class:CliOperation. A request still waiting for approval fails with cancelled and never runs; a running program is killed and answered with cancelled. Unknown ids are ignored.

AiMessage

AiMessage(role: str, content: str)

AiQuery

AiQuery(request_id: str, model_tier: str, system: str, messages: list)

AiTool

AiTool(name: str, description: str, input_schema: dict[str, Any], output_schema: dict[str, Any], timeout_ms: Optional[int] = None, read_only: bool = False)

ExposeTools

ExposeTools(tools: list[AiTool])

ToolResult

ToolResult(call_id: str, output_json: Optional[str] = None, error: Optional[str] = None, error_code: Optional[str] = None)

SetTimer

SetTimer(id: int, delay_ms: int, repeat: bool = False)

CancelTimer

CancelTimer(id: int)

SetTitle

SetTitle(title: str)

SetStatus

SetStatus(text: str)

CloseSelf

CloseSelf()

RequestCapability

RequestCapability(name: str)

EventStreamDecl

EventStreamDecl(name: str, schema_json: str, description: Optional[str] = None)

DeclareEventStreams

DeclareEventStreams(streams: list)

EmitEvent

EmitEvent(event: str, actor: str, summary: str, resource_id: str, revision_after: str, actor_id: Optional[str] = None, caused_by: Optional[str] = None, resource_scope: Optional[str] = None, payload_json: Optional[str] = None, state_ref: Optional[str] = None, revision_before: Optional[str] = None, rollback_token: Optional[str] = None, changed_resources: list = list(), suggested_trigger: Optional[str] = None)

SubscribeEventStreams

SubscribeEventStreams(request_id: str, plugin_id: str, event_names: list[str], payload_mode: str = 'full', trigger_mode: str = 'conversation', resource_id: Optional[str] = None)

UnsubscribeEventStreams

UnsubscribeEventStreams(request_id: str, subscription_id: str)

PipeOpenDirected

PipeOpenDirected(pipe_id: str, target_pane_id: int)

Ask the host for a duplex JSON pipe named pipe_id to the view in target_pane_id. Needs the pipe.open capability. pipe_id is at most MAX_PIPE_ID_BYTES (256) UTF-8 bytes; a longer one raises ValueError here.

The host answers with :class:events.PipeOpened or :class:events.PipeOpenRefused; the target gets :class:events.PipeIncoming. Sends by pipe_id returned after this effect wait for the answer (at most 64) and go out on the new connection or are dropped with the refusal.

PipeSend

PipeSend(pipe: str | int, payload: Any = None)

Send a JSON-serializable payload on a directed pipe: by name (str), the pipe’s current connection, or by handle (int, from :class:events.PipeOpened, :class:events.PipeIncoming or :class:events.PipeMessage), that connection only. Delivered to the other end as :class:events.PipeMessage. The payload is copied when the effect is applied. A send with no open connection (the connection closed, or the name is not open) is dropped and the app gets :class:events.PipeSendDropped; the other effects still apply.

Events

Modifiers

Modifiers(ctrl: bool = False, shift: bool = False, alt: bool = False, meta: bool = False)

KeyEvent

KeyEvent(key: str, modifiers: Modifiers = Modifiers(), pressed: bool = True)

MouseEvent

MouseEvent(x: float, y: float, button: Optional[str] = None, pressed: bool = False, scroll_x: float = 0.0, scroll_y: float = 0.0)

UiAction

UiAction(handler_id: str)

UiValueChange

UiValueChange(handler_id: str, value: str)

Resize

Resize(width: float, height: float)

FocusGained

FocusGained()

This pane is now the focused pane of the active context and the host window is visible and OS-focused. Delivered after :class:PaneShown.

FocusLost

FocusLost()

This pane stopped being the focused pane (another pane or context took focus, or the host window lost OS focus or was hidden). Delivered before :class:PaneHidden.

PaneShown

PaneShown()

This pane became visible: its context is active, the host window is not minimized or occluded, and no other pane is zoomed over it.

PaneHidden

PaneHidden()

This pane stopped being visible. A pane that was focused always receives :class:FocusLost first.

FocusChanged

FocusChanged(timestamp: str, duration_secs: int = 0, reason: str = 'focus_changed', pane_id: Optional[int] = None, context_name: Optional[str] = None, context_root: Optional[str] = None, cwd: Optional[str] = None)

TimerFired

TimerFired(id: int)

RenderFrame

RenderFrame(frame_id: int, elapsed: float)

FileReadResult

FileReadResult(content: Optional[bytes], error: Optional[str])

FileWriteResult

FileWriteResult(error: Optional[str])

PermissionInventory

PermissionInventory(entries: list, notice: str = '', status: str = '')

Host reply to :class:effects.ReadPermissionDecisions or :class:effects.PermissionDecision.

entries is the permission monitor’s live list. notice is empty on a plain read.

HostLogResult

HostLogResult(content: Optional[bytes], path: Optional[str], error: Optional[str])

Host reply to an effects.ReadHostLog request.

content is the raw tail text (whole log records, newline-separated) on success; error names why the log could not be reached otherwise. path is the host-resolved channel-log path, echoed back for the app to display in its empty/error state. Exactly one of content / error is set.

FilePicked

FilePicked(request_id: str, paths: list[str])

Host reply to :class:effects.OpenFilePicker: the user picked paths.

paths are absolute, canonicalized, and already registered as scoped fs grants for this pane — pass them verbatim to FileRead / FileWrite.

FilePickCancelled

FilePickCancelled(request_id: str)

Host reply to :class:effects.OpenFilePicker: the user dismissed the dialog, or the app lacks the fs.pick capability. No grant was created.

HttpResponse

HttpResponse(status: int, headers: list = list(), body: bytes = b'', error: Optional[str] = None, request_id: Optional[str] = None, tag: Optional[str] = None, truncated: bool = False, refused: Optional[str] = None)

The answer to an HttpFetch. refused names the capability (net.http) when the host refused to send the request at all, as opposed to a request that was sent and failed; error then says how the user can allow it. Show it as a refusal, not as an empty result.

McpConnected

McpConnected(request_id: str, server_id: str, error: Optional[str])

Host reply to :class:effects.McpConnect. error is None on success; otherwise it names why — an unknown server id, a spawn failure, or a missing mcp.client capability.

McpMessage

McpMessage(server_id: str, message: dict, raw: str)

One JSON-RPC message from a connected MCP server. message is the parsed object; raw keeps the exact line for diagnostics.

McpClosed

McpClosed(server_id: str, reason: str)

A connection ended — the server exited, a send failed, or the app disconnected. Every in-flight request against that server will never be answered; the app must fail them rather than wait.

CliOperationResult

CliOperationResult(request_id: str, operation_id: str, ok: bool, data: Any = None, error_code: Optional[str] = None, error: Optional[str] = None, exit_code: Optional[int] = None, stderr: Optional[str] = None, data_available: Optional[bool] = None)

Host reply to :class:effects.CliOperation, correlated by request_id. On success ok is true and data holds the program’s output, bounded by the operation’s declared limit: parsed JSON for a json operation, a string for text. On failure ok is false and error_code is one of invalid_request, disabled, capability_missing, busy, unknown_operation, package_invalid, invalid_argument, flag_like_argument, executable_missing, executable_mismatch, executable_not_self_contained, denied, approval_timeout, audit_failed, launch_failed, timeout, output_too_large, cancelled, nonzero_exit or bad_output; error is a human-readable message. For nonzero_exit, exit_code is set, stderr holds a bounded tail, and data holds the program’s stdout when it passes the same bound and format check as a success (parsed JSON for a json operation, a string for text); data_available says whether it did, and unparseable output is never put in data. A failure other than a nonzero exit, timeout or cancellation means the program did not run.

AiResponse

AiResponse(request_id: str, content: Optional[str], tokens_in: int, tokens_out: int, error: Optional[str])

ToolCall

ToolCall(call_id: str, name: str, input_json: str, caller_id: str, authorization: Optional[str] = None)

EventSubscriptionResult

EventSubscriptionResult(request_id: str, subscription_id: Optional[str], error: Optional[str])

EventUnsubscriptionResult

EventUnsubscriptionResult(request_id: str, removed: bool, error: Optional[str])

PluginEvent

PluginEvent(subscription_id: str, plugin_id: str, event: str, event_id: int, resource_id: str, trigger_mode: str, summary: Optional[str], payload_json: Optional[str], state_ref: Optional[str], created_at: str)

DeclareEventStreamsResult

DeclareEventStreamsResult(streams: Optional[list], error: Optional[str])

EmitEventResult

EmitEventResult(sequence: Optional[int], error: Optional[str])

SurfaceReady

SurfaceReady(texture_handle: int, width: int, height: int)

SurfaceResized

SurfaceResized(texture_handle: int, width: int, height: int)

PipePayload

PipePayload(binary: Optional[bytes] = None, json: Optional[str] = None)

PipeMessage

PipeMessage(handle: int = 0, payload: PipePayload = PipePayload(), pipe_id: str = '', data: Optional[object] = None)

PipeOpened

PipeOpened(pipe_id: str, handle: int)

This app’s :class:effects.PipeOpenDirected for pipe_id was accepted. handle names the connection; sends by name that waited for the answer have gone out on it.

PipeOpenRefused

PipeOpenRefused(pipe_id: str, reason: str)

This app’s :class:effects.PipeOpenDirected for pipe_id was refused and the sends that waited for it were dropped. reason is one of denied, no_target, not_a_plugin, out_of_reach, in_use, name_conflict, opener_unplaced, target_unavailable, opener_full (this app holds as many connections as its input has room to close, or its input is full) or name_too_long (over effects.MAX_PIPE_ID_BYTES).

PipeSendDropped

PipeSendDropped(pipe: str | int, reason: str)

A :class:effects.PipeSend on pipe (a name or handle) was dropped because no connection was open for it: it closed (after :class:PipeClosed), its open was refused, or it was never opened. reason says which.

PipeIncoming

PipeIncoming(pipe_id: str, handle: int, peer_pane_id: int)

Pane peer_pane_id opened directed pipe pipe_id to this app. Reply by name or on handle.

PipeClosed

PipeClosed(pipe_id: str, handle: int, reason: str)

Directed pipe connection handle (named pipe_id) ended: the other end’s view closed (reason == "peer_closed"), its app reloaded ("peer_reloaded"), or either end moved to another context ("moved"). A reopen is a new connection with a new handle.

StateChanged

StateChanged(scope: str, values: dict, source: str = 'external', error: Optional[str] = None)

A state scope’s backing file changed outside this app’s own persist flow — an external edit (CLI, agent, editor), or a persist this app lost to a concurrent external write (disk wins: the dropped persist is answered with this event).

values is the scope’s full value set after the change; the runtime has already replaced the scope wholesale (deleted keys are gone — never a merge) before dispatching this event, so state.get reads are fresh inside update(). When error is set the file could not be decoded: the previous values are kept and persists to the scope are blocked until a successful re-read.

CapabilityGranted

CapabilityGranted(name: str)

CapabilityDenied

CapabilityDenied(name: str)

State and Logging

ComponentSetter

A deferred component-state update returned by use_state.

StateSnapshot

StateSnapshot(values: Mapping[str, Any], raw_values: Mapping[str, bytes], scoped: Mapping[str, Mapping[str, Any]] = dict(), scopes: tuple[str, ...] = ('global',))

StateProxy

get(key: str, default: Any = None, scope: Optional[str] = None)

raw(key: str)

all(scope: Optional[str] = None)

load(defaults: Mapping[str, Any], scope: Optional[str] = None)

Return a fresh dict merging defaults with stored state in scope.

set(key: str, value: Any, scope: Optional[str] = None)

patch(updates: Optional[Mapping[str, Any]] = None, scope: Optional[str] = None, persist: bool = False, **kw)

Return a SetState (or PersistState when persist=True) effect.

scopes()

The scopes this app declared in its manifest, ordered; the first entry is the default scope.

ComponentState

ComponentState(key: str, scope: Optional[str] = None)

State owned by one explicitly keyed component.

A component key is stable app-defined identity, not a renderer identity. The state is stored beneath a reserved key in the normal state snapshot, which keeps ordinary restore and PersistState behaviour intact.

component(key: str, scope: Optional[str] = None)

Declare state for a component with a stable explicit key.

use_state(key: str, name: str, default: Any = None, scope: Optional[str] = None)

Read local state for component key and return its effect setter.

LogProxy

debug(msg: str)

info(msg: str)

warn(msg: str)

error(msg: str)

UI Components

Plexi SDK — Declarative Host-Rendered UI Component Library (plexi_sdk.ui).

All components in this module serialize to a declarative UiNode tree via to_node() and are rendered natively by the Plexi host.

Usage::

from plexi_sdk import theme
from plexi_sdk.ui import (
    SurfaceHeader, Badge, Button, Card, Column, DataTable, Divider,
    FooterKeys, HStack, Heading, Label, Pending, Scrollable,
    Section, SelectList, Skeleton, Spacer, Text, TextInput,
    SPACE_SM, SPACE_MD,
)

BadgeColor

BadgeColor = Literal['accent', 'success', 'warning', 'danger', 'neutral', 'red', 'green', 'yellow']

Semantic color roles accepted by Badge and Banner.

TextColor

TextColor = Literal['accent', 'success', 'warning', 'danger', 'neutral', 'muted', 'red', 'green', 'yellow']

Semantic color roles accepted by Text, Label and Heading (the BadgeColor roles plus "muted"), in addition to #rrggbb / #rrggbbaa hex strings from plexi_sdk.theme.

ensure_visible(scroll_offset: float, viewport_h: float, item_top: float, item_bottom: float, margin: float = 0.0)

Return a clamped scroll offset that keeps [item_top, item_bottom] visible.

move_cursor(event_or_key: Any, count: int, selected: int = 0)

Compute the next 0-based cursor index for standard list navigation keys.

Handles j / down, k / up, g / home, and G / end. Returns the new clamped index in 0..count-1, or None if event_or_key is not a list navigation key or count <= 0.

Component

Base class for all declarative UI components.

Every concrete component implements :meth:to_node returning a JSON-serializable dictionary consumed by the host UI decoder.

Keyed

Keyed(child: Component, key: str)

Give a component a stable explicit key for lists and local state.

Column

Column(children: Sequence[Component] | None = None, gap: float | None = None, padding: float | tuple[float, float] | tuple[float, float, float, float] = 0.0, align: str = 'start', justify: str = 'start', grow: bool = False)

Vertical stack of child components.

align places children across the column: "start" (left, the default), "center" or "end". Leftover height is shared equally by every Spacer(grow=True) child, so [Spacer(grow=True), child, Spacer(grow=True)] centers child vertically and a single grow spacer pins what follows it to the bottom. justify places children down a column without grow spacers: "start" (the default), "center", "end" or "space-between"; the column then fills the height it is given.

HStack

HStack(children: Sequence[Component] | None = None, gap: float | None = None, align: str = 'center', justify: str = 'start', grow: bool = False)

Horizontal stack of child components (Row alias).

align is the cross axis, as on Column: it places children at the top ("start"), the middle ("center", the default) or the bottom ("end") of the row. justify places them along the row: "start" (the default), "center", "end" or "space-between". Leftover width is shared equally by every Spacer(grow=True), Column(grow=True) and Row(grow=True) child, which then takes precedence over justify; a Column that does not grow is as wide as its content. A Text child too long for the row wraps in the width its later siblings leave.

Card

Card(children: Sequence[Component] | None = None, padding: float = SPACE_MD, gap: float | None = SPACE_SM, bg_color: str | None = None, border_color: str | None = None, radius: float = RADIUS_MD)

Elevated surface container with rounded border and inner padding.

Scrollable

Scrollable(child: Component, horizontal: bool = False)

Scrollable viewport wrapping a single child component.

Grid

Grid(columns: int, children: Sequence[Component] | None = None, gap: float = SPACE_SM)

Multi-column grid layout composed onto rows and columns.

SurfaceHeader

SurfaceHeader(title: str, subtitle: str = '', accent: str | None = None)

Top application header bar with title and optional subtitle.

Section

Section(title: str, children: Sequence[Component] | Component | None = None, *more_children, gap: float = SPACE_SM)

Titled section header with a divider, optionally wrapping body children.

Heading

Heading(text: str = '', size: float = TEXT_HEADING, color: str | None = None, align: str = 'left', truncate: bool = False)

Bold section or view heading.

Label

Label(text: str = '', size: float | None = None, color: str | None = None, bold: bool = False, elide: bool = False, tone: str = 'body', align: str = 'left', truncate: bool = False)

Single-line or body text label with optional semantic tone or color.

Text

Text(text: str = '', size: float = 13.0, color: str = '', bold: bool = False, italic: bool = False, monospace: bool = False, truncate: bool = False, align: str = 'left', tone: str = '')

Declarative text primitive with font size, styling, color, truncation, and alignment.

Spacer

Spacer(size: float = SPACE_MD, grow: bool = False, flex: bool = False)

Fixed or flex gap.

grow=True in a Column takes an equal share of the column’s leftover height with every other grow spacer in it.

Divider

Divider(color: str | None = None)

Horizontal rule separating vertical sections.

Badge

Badge(label: str = '', color: BadgeColor = 'neutral', text: str = '', tone: BadgeColor | None = None)

Semantic status pill (accent, success, warning, danger, neutral).

FooterKeys

FooterKeys(shortcuts: list[tuple[Any, str]] = list(), divider: bool = True)

Bottom-pinned keybinding hint bar.

Button

Button(label: str, on_click: str = '', style: str = 'secondary', disabled: bool = False)

Interactive button dispatching UiAction(on_click) when activated.

Actions

Actions(buttons: Sequence[Button | Keyed] | None = None, actions: Sequence[Button | Keyed] | None = None, gap: float = SPACE_SM, align: str = 'center')

Horizontal row of Button components (ActionBar alias).

Wrap buttons in Keyed to preserve their identity when actions change. align places the buttons at the top, middle (the default) or bottom of the row. Buttons that do not fit the pane width wrap onto further lines as whole buttons; a label never breaks inside a word.

TextInput

TextInput(id: str = '', value: str = '', placeholder: str = '', on_change: str = '', on_submit: str = '', password: bool = False, autofocus: bool = False, node_id: str = '')

Single-line editable text input rendered natively by the host (TextEdit alias).

The host sends UiValueChange(on_change, value) on every edit and UiAction(on_submit) when Enter is pressed in the field. Both ids default to id. There is no multi-line input yet.

FormField

FormField(id: str, label: str, value: str = '', placeholder: str = '', required: bool = False, password: bool = False, autofocus: bool = False, on_change: str = '', on_submit: str = '')

Labeled TextInput column with optional required indicator.

Checkbox

Checkbox(node_id: str, label: str = '', checked: bool = False, disabled: bool = False)

Boolean checkbox control dispatching UiAction(node_id) on click.

Toggle

Toggle(node_id: str, value: bool | None = None, label: str = '', on: bool | None = None, disabled: bool = False)

Boolean toggle control (Switch alias).

Radio

Radio(node_id: str, options: list[str] | None = None, selected: int = 0, disabled: bool = False)

Single-choice radio group dispatching UiAction(f"{node_id}:{idx}").

Slider

Slider(node_id: str, value: float = 0.0, min: float = 0.0, max: float = 1.0, step: float = 0.01, disabled: bool = False)

Numeric range slider control with decrement/increment buttons and progress bar.

Select

Select(node_id: str, options: list[str] | None = None, selected: int | None = None, placeholder: str = 'Select…', disabled: bool = False)

Single-choice option selector.

DateTimePicker

DateTimePicker(node_id: str, value: str = '', mode: str = 'date', disabled: bool = False)

Date/time input field.

SelectList

SelectList(items: list[Any], selected_idx: int = 0, scroll_height: float = 0, selected: int | None = None, on_select: str | None = None)

Scrollable, selectable list view with keyboard and click navigation.

items may be:

  • list[dict] with name (or label) and optional description, leading, trailing
  • list[str] of row labels
  • list[Component] of custom row components

When on_select is set, clicking row i dispatches UiAction(f"{on_select}:{i}"). Use :meth:SelectList.move_cursor (or top-level :func:move_cursor) in update() to handle j/k/arrow keys.

Breadcrumb(items: list[str] | None = None)

Horizontal trail of path segments separated by /.

Tabs

Tabs(*args, tabs: list[Any] | None = None, active: int = 0, node_id: str = 'tabs')

Tabbed container or standalone tab bar (TabBar alias).

Can be constructed either with (label, panel_component) pairs::

Tabs([("Overview", overview_panel), ("Logs", logs_panel)], active=0, node_id="tabs")

or as a standalone tab bar::

TabBar("gallery-tabs", tabs=["Overview", "Details", "Logs"], active=0)

Pagination

Pagination(node_id: str, page: int = 0, total: int = 1)

Prev / page-indicator / Next pagination bar.

DataTable

DataTable(columns: list[str] | None = None, rows: list[list[Any]] | None = None, selected: int | None = None, selected_idx: int | None = None, on_select: str | None = None)

Structured multi-column table with header row, selection, and row-click action (Table alias).

When on_select is set, clicking row i dispatches UiAction(f"{on_select}:{i}").

Banner(text: str, tone: BadgeColor = 'neutral', title: str = '', dismissible: bool = False, node_id: str = '')

Status banner with semantic tone badge and message.

ProgressBar

ProgressBar(value: float = 0.0, max_value: float = 1.0, label: str = '', indeterminate: bool = False)

Horizontal progress indicator (Progress alias).

Spinner

Spinner(label: str = '')

Animated indeterminate loading spinner.

Skeleton

Skeleton(rows: int = 1, height: float = 14.0)

Placeholder loading lines.

Pending

Pending(active: bool, child: Component, placeholder: Component | None = None)

Renders placeholder while active is true, otherwise child.

KeyValue

KeyValue(rows: list[tuple[str, str]] | None = None)

Two-column key/value metadata list.

CodeBlock

CodeBlock(code: str = '', language: str = '')

Monospace code block with optional language badge.

Avatar

Avatar(label: str = '', size: float = 28.0)

Initials badge derived from a display name.

Icon

Icon(name: str = '', size: float = 16.0, tone: str = 'body')

Named icon glyph.

Tooltip

Tooltip(text: str, child: Component)

Inline tooltip hint displayed alongside a child component.

Accordion

Accordion(node_id: str, title: str, child: Component, open: bool = False)

Collapsible section header + body.

EmptyState

EmptyState(title: str, description: str = '', icon: str = '')

Centered empty-state message with optional icon and description.

Modal(node_id: str, title: str, child: Component, open: bool = True)

Framed modal dialog block.

CanvasRect

CanvasRect(x: float, y: float, width: float, height: float, fill: str, radius: float = 0.0)

CanvasCircle

CanvasCircle(x: float, y: float, radius: float, fill: str)

CanvasLine

CanvasLine(x1: float, y1: float, x2: float, y2: float, color: str = '#cdd6f4', width: float = 1.0)

CanvasText

CanvasText(x: float, y: float, text: str, size: float = 14.0, color: str = '#ffffff', bold: bool = False, align: str = 'left_top', monospace: bool = False)

CanvasCommand

CanvasCommand = CanvasRect | CanvasCircle | CanvasLine | CanvasText

Any one drawing command accepted by Canvas.

Canvas

Canvas(commands: Sequence[CanvasCommand] | None = None, width: float = 640.0, height: float = 360.0, grow: bool = True, fit: str = 'fill', key: str = '', on_click: str = '')

2D vector drawing surface rendered natively by the host.

Testing

Headless snapshot testing for Plexi widgets.

Spawns the plexi binary with --render, feeds it DrawCommand JSON, reads back PNG bytes. Provides pixel-level assertions and snapshot file helpers.

render_draw_commands(commands: list[dict], width: int, height: int, background: str = DEFAULT_BG)

Feed draw commands to the headless renderer, return PNG bytes.

Args: commands: list of PGAP draw command dicts (rect, text, line, …). width: viewport width in pixels. height: viewport height in pixels. background: CSS hex colour string for the background fill.

Returns: Raw PNG bytes.

Raises: RuntimeError if the binary is not found or exits nonzero.

decode_png(png_bytes: bytes)

Decode an RGBA 8-bit PNG to (width, height, raw_rgba_bytes).

Pure stdlib implementation using zlib + struct. Only handles RGBA 8-bit PNGs — which is exactly what tiny-skia produces.

Raises: ValueError on an unrecognised PNG or unsupported colour type/bit depth.

pixel_at(png_bytes: bytes, x: int, y: int)

Return (r, g, b, a) of the pixel at (x, y).

hex_to_rgba(hex_color: str)

Convert a CSS hex color string to (r, g, b, a).

Supports #RGB, #RRGGBB, and #RRGGBBAA. Alpha defaults to 255 when not specified.

assert_pixel(png_bytes: bytes, x: int, y: int, expected: Union[str, tuple[int, int, int, int]], tolerance: int = 4)

Assert the pixel at (x, y) matches the expected color within per-channel tolerance.

Args: png_bytes: raw PNG bytes from render_draw_commands. x, y: pixel coordinates. expected: CSS hex string (e.g. “#ff0000”) or (r, g, b, a) tuple. tolerance: per-channel absolute tolerance (default 4).

Raises: AssertionError with a diagnostic message on mismatch.

save_snapshot(png_bytes: bytes, path: Union[str, Path])

Write PNG bytes to path. Creates parent directories as needed.

PluginHarness

PluginHarness(plugin_path: 'str | Path', width: int = 800, height: int = 600, timeout: float = 5.0, host_log_path: 'str | Path | None' = None)

Headless runner for Plexi Python apps.

Spawns the app script as a subprocess, communicates over stdin/stdout using the PGAP v3 protocol. No display or running Plexi host required.

Usage::

with PluginHarness("my_app.py", width=400, height=300) as h:
    cmds = h.run(1)                  # step one render frame
    h.key("enter")                   # inject a key event
    cmds = h.run(1)                  # render again to see effects
    h.assert_pixel(10, 10, "#1e1e2e")  # pixel assertion (needs plexi binary)

Types

CapabilityDeniedError

Raised when the host rejects a brokered call because the app’s manifest didn’t declare the required capability. Distinct from generic RuntimeError so apps can catch the gate-denial path explicitly.

VideoHandle

VideoHandle(handle_id: int, width: int, height: int, fps: float, duration_ms: int, pipe: 'object')

Video handle. handle_id is opaque, passed back to video control effects. pipe delivers decoded RGBA8 frames of length width * height * 4.

RectCommand

RectCommand(x: float, y: float, w: float, h: float, fill: str, radius: float = 0.0)

Typed constructor for ctx.rect(). Validates geometry at construction.

TextCommand

TextCommand(x: float, y: float, text: str, size: float, color: str, monospace: bool = False, bold: bool = False, align: str = 'left_top', max_width: Optional[float] = None, elide: bool = True, selectable: bool = False)

Typed constructor for ctx.text(). Validates align at construction.

BadgeCommand

BadgeCommand(x: float, y_center: float, label: str, fill: str = '', fg: str = '', font_size: float = 11.0, radius: float = 8.0)

Typed constructor for ctx.badge().

ShortcutPair

ShortcutPair(keys: List[str], description: str = '')

Typed constructor for one entry in ctx.shortcuts() pairs.

NotifyOption

NotifyOption(label: str, value: Optional[str] = None, shortcut: Optional[str] = None)

Typed constructor for one option in ctx.notify_choice().

Theme

Live theme singleton and color helpers.

Populated from the host Init payload so app chrome tracks the host theme (light/dark + user overrides in config.toml). Until Init arrives the attributes hold the built-in dark defaults.

Process-wide instance theme is mutated in place on Init. Never rebind the name, only set attributes.

theme.is_dark is True when the background luminance is below 0.5.

Theme

Theme()

Mutable bag of semantic color roles, each a #rrggbb string.

is_dark is a computed boolean: True when the background luminance is below 0.5 (i.e. the theme is dark-mode). Derived from bg on every update_from call so it stays in sync with theme hot-reloads.

reset()

update_from(payload: 'dict | None')

Overlay host-provided roles. Unknown keys and non-string/empty values are ignored so a partial payload never blanks a color.

PluginPalette

PluginPalette(dark: 'dict[str, str]', light: 'dict[str, str]')

Light/dark palette for app-defined color tokens.

Both dicts must have the same keys. resolve(theme) returns the matching set based on theme.is_dark.

resolve(theme: Theme)

Return the dark or light token set based on theme.is_dark.

rgba(r: int, g: int, b: int, a: int = 255)

Return an 8-digit hex color string #rrggbbaa.

dim(hex_color: str, alpha: int)

Return hex_color with the given alpha (0-255). Strips existing alpha.

Protocol Types

AiResponse

AiResponse(tokens_in: int, tokens_out: int, content: Optional[str] = None, error: Optional[str] = None)

Result of Emitter.ai_query. tokens_in/tokens_out are zero on error.

MidiPortInfo

MidiPortInfo(id: str, name: str, default: bool)

One MIDI port. Mirrors MidiPortWire in the Rust protocol.

MidiDeviceList

MidiDeviceList(inputs: list, outputs: list)

Result of Emitter.list_midi_devices.

AudioDeviceInfo

AudioDeviceInfo(id: str, name: str, default: bool)

One audio device. Mirrors AudioDeviceWire in the Rust protocol.

AudioDeviceList

AudioDeviceList(inputs: list, outputs: list)

Result of Emitter.list_audio_devices.