Extension views
An extension view is a GUI that an extension describes once, as data. The extension mounts the view with ctx.ui.mountView, and every client attached to the session draws it with its own controls: the terminal draws rows, and a web page draws HTML. A view is a tree of nodes (text, lists, inputs, buttons, a grid), the intents a user can raise, and optionally alternatives for different clients, key bindings and a drawing. A view fills a slot such as a panel, a widget row or a dialog. No client runs extension code.
Differs from Pi. Pi has no views: its
ctx.ui.customcomponents draw in the terminal only. Views are the PiG-additive feature D614. Stock PiG attaches no view client, soctx.ui.viewAbilities()returnsnullandctx.ui.mountViewrejects with codeunsupporteduntil a Piglet attaches one.
This page uses the Node SDK, because a .mjs extension loads without a build. The calls in each SDK names the same calls for Go, Python, Rust and Lisp. What the clients draw says what each client does with a view at this version.
Try it
The terminal draws views when the active Piglet sets viewClient: terminal. Save this Piglet in the directory of the extension file and start it there with pig --piglet ./views.yaml.
name: views
description: "Draw extension views in the terminal and serve them to other clients."
viewClient: terminal
viewEndpoint: socket
extensions:
- name: todo
origins:
- local:./todo.mjsA Piglet's extensions and the -e option load a .mjs file. The extensions folders load only .ts and .js files (Extensions). After you edit the extension, type /reload.
viewEndpoint: socket serves the session's views on the Unix socket <agent directory>/view-endpoint/<pid>.sock, for example under ~/.pig/agent/view-endpoint/. A client program of the same user attaches there. The pig binary contains no web page and no web server. The reference web client is in a checkout of the PiG repository, in examples/ui-view-web, and needs Node:
node examples/ui-view-web/bridge.mjs --connect ~/.pig/agent/view-endpoint
node examples/ui-view-web/bridge.mjs -- -e ./todo.mjsThe first command attaches a web page to the running terminal session. The second command starts a pig of its own for each page and needs no Piglet. Both print one line that names the file to open: ui-view-web: http://127.0.0.1:<port>/ (open: <dir>/open.html).
Open that file with the path the line printed: open <path> on macOS, xdg-open <path> on Linux, Start-Process <path> in PowerShell on Windows. The file sends your browser to the page's address, http://127.0.0.1:<port>/#<code>. The path holds no code, and only you can read the file. The address works once: the page takes the code out of the address bar at once, hands it to the bridge in a request body and is given a session secret in exchange, which it keeps for that tab only. No address holds a secret after the first load, and the browser's history may keep the used address, which opens nothing. A code lasts ten minutes. When it is used, or when the ten minutes pass unused, the bridge writes the next one into open.html and address (in the same private directory), so to open another tab, open open.html again. A replayed, expired or wrong code is refused, and the page then says to open the file again. This is why: a log, a terminal recording, a shared screen or a browser's history must not hold an address that still works. Do not hand the address itself to a command: the argument list of a command can be read by every user of a Linux machine. Keep the secret to yourself: with the second command, a process on your machine that has it can prompt the pig the bridge starts, as you. The bridge removes the files when it ends. --print-token, or UI_VIEW_WEB_PRINT_TOKEN=1, prints ui-view-web: http://127.0.0.1:<port>/#<code> as the line instead and makes no file; one run gives one code for one exchange.
A complete extension
This extension mounts a todo list in the panel slot. A terminal draws the plain view. A web page draws the alternative. Both show the same state. The key c opens a second mount, a dialog that asks before it removes the done items.
// todo.mjs: one todo list for the terminal and a web page.
export default function todo(pi) {
const items = [
{ id: "milk", label: "Buy milk", done: false },
{ id: "letter", label: "Send the letter", done: true },
{ id: "plants", label: "Water the plants", done: false },
];
let mount = null;
let confirm = null;
const open = () => items.filter((item) => !item.done).length;
const list = () => ({
kind: "select-list",
id: "items",
items: items.map((item) => ({ value: item.id, label: `${item.done ? "[x]" : "[ ]"} ${item.label}` })),
});
const plain = () => ({ root: { kind: "vstack", children: [{ kind: "text", text: `Todo: ${open()} open. Press c to clear the done items.` }, list()] } });
const rich = () => ({ root: { kind: "vstack", gap: 1, children: [{ kind: "markdown", text: `# Todo\n\n**${open()}** of ${items.length} open.` }, list()] } });
const removed = { type: "object", properties: { removed: { type: "integer" } }, required: ["removed"] };
const content = () => ({
title: "Todo",
view: plain(),
alternatives: [{ when: { any: [{ all: [{ claim: "client.kind", op: "equals", value: "web" }] }] }, view: rich() }],
intents: [
{ name: "todo.toggle", nodeKey: "items", arg: { type: "object", properties: { value: { type: "string" } }, required: ["value"] } },
{ name: "todo.clear", arg: { type: "object" }, answer: removed },
],
bindings: [{ key: "c", intent: "todo.clear", name: "Clear done" }],
a11y: [{ node: "items", name: "Todo items", role: "list" }],
focus: [{ node: "items", request: "mount" }],
fallback: { kind: "text", text: "The todo list does not fit this client." },
});
// The dialog. Its two bindings raise one intent with different arguments.
const question = () => ({
title: "Clear done items",
view: { root: { kind: "text", text: `Remove ${items.length - open()} done items? Press y or n.` } },
intents: [
{ name: "todo.confirm", arg: { type: "object", properties: { yes: { type: "boolean" } }, required: ["yes"] }, answer: removed },
{ name: "todo.cancel", arg: { type: "object" }, answer: removed, dismiss: true },
],
bindings: [{ key: "y", intent: "todo.confirm", arg: { yes: true }, name: "Remove" }, { key: "n", intent: "todo.confirm", arg: { yes: false }, name: "Keep" }],
});
const clear = () => {
const before = items.length;
items.splice(0, items.length, ...items.filter((item) => !item.done));
return { removed: before - items.length };
};
// Mount once, when a client that draws panels is attached.
const show = async (abilities, ctx) => {
if (!abilities || mount || !abilities.slots.includes("panel")) return;
mount = (await ctx.ui.mountView({ key: "todo", slot: "panel", ...content() })).mount;
};
pi.onViewAbilities(show);
pi.on("session_start", (_event, ctx) => show(ctx.ui.viewAbilities(), ctx));
pi.onViewIntent(async (inv, ctx) => {
let answer;
if (inv.intent === "todo.toggle") {
const item = items.find((entry) => entry.id === inv.arg.value);
if (!item) return { outcome: "refused", error: "no such item" };
item.done = !item.done;
} else if (inv.intent === "todo.clear") {
// Ask in a dialog when a client draws dialogs. Only the extension closes a dialog.
if (ctx.ui.viewAbilities()?.slots.includes("dialog")) {
if (!confirm) confirm = (await ctx.ui.mountView({ key: "todo-confirm", slot: "dialog", ...question() })).mount;
return { outcome: "done", answer: { removed: 0 } };
}
answer = clear();
} else if (inv.intent === "todo.confirm" || inv.intent === "todo.cancel") {
answer = inv.arg.yes ? clear() : { removed: 0 };
await ctx.ui.removeView(confirm);
confirm = null;
} else return { outcome: "refused", error: "unknown intent" };
mount = (await ctx.ui.updateView(mount, content())).mount;
return { outcome: "done", answer };
});
}The same extension in Go
A Go extension is a package with func Extension() *sdk.Extension, in a module that requires github.com/MichaelKinsy/PiG/extensions/sdk. pig extension init ./todo --lang go creates the module (Extensions). PiG builds the package when it loads it and at every /reload. Name the directory in the Piglet's origins (local:./todo) or with -e ./todo.
The Go SDK takes the records of this page as structs with the same member names, and the kit package builds the nodes. Go names lists them. A handler runs on a goroutine of its own, so guard your state. This example is todo.mjs without the dialog.
// todo/extension.go: the todo list of todo.mjs as a Go extension.
package todo
import (
"encoding/json"
"fmt"
"slices"
"sync"
"github.com/MichaelKinsy/PiG/extensions/sdk"
"github.com/MichaelKinsy/PiG/extensions/sdk/kit"
)
type item struct {
id, label string
done bool
}
// Extension returns a new instance. PiG calls it at every load and reload.
func Extension() *sdk.Extension {
var (
mu sync.Mutex
mount *sdk.ViewRef
items = []*item{{id: "milk", label: "Buy milk"}, {id: "letter", label: "Send the letter", done: true}, {id: "plants", label: "Water the plants"}}
)
content := func() sdk.ViewContent {
open := 0
rows := make([]kit.SelectItem, len(items))
for i, it := range items {
box := "[x]"
if !it.done {
box = "[ ]"
open++
}
rows[i] = kit.SelectItem{Value: it.id, Label: box + " " + it.label}
}
list := func() kit.Node { return kit.NewSelectList("items", rows, 8) }
web := sdk.ViewWhen{Any: []sdk.ViewWhenAll{{All: []sdk.ViewClause{{Claim: "client.kind", Op: "equals", Value: "web"}}}}}
rich := kit.NewMarkdown(fmt.Sprintf("# Todo\n\n**%d** of %d open.", open, len(items)), 1, 0)
return sdk.ViewContent{
Title: "Todo",
View: kit.View{Root: kit.NewContainer(kit.NewText(fmt.Sprintf("Todo: %d open. Press c to clear the done items.", open), 1, 0), list())},
Alternatives: []sdk.ViewAlternative{{When: web, View: kit.View{Root: kit.NewContainer(rich, list())}}},
Intents: []sdk.ViewIntent{
{Name: "todo.toggle", NodeKey: "items", Arg: sdk.ViewShape{Type: "object", Properties: map[string]sdk.ViewShape{"value": {Type: "string"}}, Required: []string{"value"}}},
{Name: "todo.clear", Arg: sdk.ViewShape{Type: "object"}, Answer: &sdk.ViewShape{Type: "object", Properties: map[string]sdk.ViewShape{"removed": {Type: "integer"}}, Required: []string{"removed"}}},
},
Bindings: []sdk.ViewBinding{{Key: "c", Intent: "todo.clear", Name: "Clear done"}},
A11y: []sdk.ViewA11y{{Node: "items", Name: "Todo items", Role: "list"}},
Focus: []sdk.ViewFocus{{Node: "items", Request: "mount"}},
Fallback: kit.NewText("The todo list does not fit this client.", 1, 0),
}
}
// Mount once, when a client that draws panels is attached.
show := func(ctx sdk.Context, abilities *sdk.ViewAbilities) {
mu.Lock()
defer mu.Unlock()
if abilities == nil || mount != nil || !slices.Contains(abilities.Slots, sdk.ViewSlotPanel) {
return
}
status, err := ctx.MountView(sdk.ViewMount{Key: "todo", Slot: sdk.ViewSlotPanel, ViewContent: content()})
if err != nil {
ctx.Notify("todo: "+err.Error(), "error")
return
}
mount = &status.Mount
}
ext := sdk.New("todo")
ext.OnViewAbilities(show)
ext.OnSessionStart(func(ctx sdk.Context, _ map[string]any) (any, error) {
show(ctx, ctx.ViewAbilities())
return nil, nil
})
ext.OnViewIntent(func(in sdk.ViewIntentInvocation) sdk.ViewIntentResult {
mu.Lock()
defer mu.Unlock()
result := sdk.ViewIntentResult{Outcome: "done"}
switch in.Intent {
case "todo.toggle":
var arg struct {
Value string `json:"value"`
}
if err := json.Unmarshal(in.Arg, &arg); err != nil {
return sdk.ViewIntentResult{Outcome: "failed", Error: err.Error()}
}
i := slices.IndexFunc(items, func(it *item) bool { return it.id == arg.Value })
if i < 0 {
return sdk.ViewIntentResult{Outcome: "refused", Error: "no such item"}
}
items[i].done = !items[i].done
case "todo.clear":
before := len(items)
items = slices.DeleteFunc(items, func(it *item) bool { return it.done })
// The answer is JSON of the declared shape.
result.Answer = json.RawMessage(fmt.Sprintf(`{"removed":%d}`, before-len(items)))
default:
return sdk.ViewIntentResult{Outcome: "refused", Error: "unknown intent"}
}
// Update through the handler's context, then answer.
status, err := in.Context.UpdateView(sdk.ViewUpdate{Mount: *mount, ViewContent: content()})
if err != nil {
return sdk.ViewIntentResult{Outcome: "failed", Error: err.Error()}
}
mount = &status.Mount
return result
})
return ext
}Go names
- Nodes:
kit.NewContainer(children...)(a column),kit.NewBox(paddingX, paddingY, children...),kit.NewText(text, paddingX, paddingY),kit.NewTruncatedText(text, paddingX, paddingY),kit.NewMarkdown(text, paddingX, paddingY),kit.NewLines(lines),kit.NewSpacer(lines),kit.NewDynamicBorder(color),kit.NewSelectList(id, items, maxVisible),kit.NewSettingsList(id, items, maxVisible),kit.NewInput(id),kit.NewEditor(id),kit.NewMouseRegion(id, child),kit.NewScrollView(id, child)andkit.NewGrid(id, columns, cells). Set the other members on the struct that a constructor returns. - Images:
kit.NewImage(data, mimeType)takes the decoded bytes of a photograph and returns a*kit.Image. SetMaxWidthCells,MaxHeightCellsandImageID(all*int),Filename,FallbackColorandIDon the struct. The node carries the bytes in the view'simageslist; the kit does this for you. - Ids: only the constructors with an
idargument make a node with an id. A box, a text, a container and a markdown node have none in Go. To give a drawing a node, name akit.NewScrollView(id, child)inNode, or leaveNodeempty. - Content:
sdk.ViewContent{Title, View, Intents, Bindings, Alternatives, Drawing, A11y, Focus, Fallback}.Viewis akit.View{Root: node},Fallbackis a node andDrawingis a*sdk.ViewDrawing.sdk.ViewMount{Key, Slot, Target, ViewContent}andsdk.ViewUpdate{Mount, ViewContent}embed it. The slots are constants such assdk.ViewSlotPanelandsdk.ViewSlotDialog. - Intents:
sdk.ViewIntent{Name, NodeKey, Arg, Answer, Cancellable, TimeoutMs, WhenHidden, Dismiss}.Argis asdk.ViewShapeandAnsweris a*sdk.ViewShape. In the handler,in.Argand the result'sAnswerarejson.RawMessage. - Other records:
sdk.ViewBinding{Key, Gesture, Intent, Arg, Name},sdk.ViewA11y{Node, Name, Role, ...},sdk.ViewFocus{Node, Request},sdk.ViewAlternative{When, View, Drawing}. - Drawings:
sdk.ViewDrawing{Profile, Node, Viewport, Shapes, Regions},*sdk.ViewViewport{X, Y, Width, Height, Fit},sdk.ViewDrawShape{Kind, Key, Fill, Stroke, X, Y, Width, Height, ...}(one struct for every kind, withfloat64numbers) andsdk.ViewRegion{Key, Shape, Gestures, Intent, Name, Role}.abilities.Drawingis nil when no client draws a profile, andabilities.Drawing.Profilesis a[]string. - Errors: a rejected operation returns a
*sdk.ViewError. Match it witherrors.Asand read itsCode, for examplesdk.ViewErrorUnsupported.
Mount, update and end
ctx.ui.viewAbilities()returns what the attached clients draw, ornullwhen no client is attached:{ slots, nodes, markdown, imageFormats, limits, input, claims, slotClaims, drawing }.slotsandnodesare arrays of strings.drawingis absent when no client draws a profile. With several clients the record is their merge: the union of the slots, node kinds and drawing profiles, the largest limits, and the claims that every client states with the same value.pi.onViewAbilities((abilities, ctx) => ...)runs when the first client attaches, when the abilities change and when the last client leaves (null). It does not run for the state the extension starts in, so also readctx.ui.viewAbilities()atsession_start. A mount stays live while no client is attached, and a client that attaches later is sent it.ctx.ui.mountView({ key, slot, target, title, view, intents, bindings, alternatives, drawing, a11y, focus, fallback })mounts the view. Onlykey,slotandvieware required. Omit a member that you do not use.keyis 1 to 128 bytes and names the mount inside your extension.viewis{ root: node }.titleis the label of the mount in a tab or a list of views: at most 64 bytes on one line.targetis required for three slots only:{ toolCallId }fortool-card,{ messageType }formessageand{ entryType }forentry.fallbackis one node: a client that cannot draw the content is sent it, markeddegraded, when another attached client can draw the content.- Every operation returns a promise of
{ mount, state }.mountis the ref{ key, epoch, rev }. Pass the newest ref to the next operation: an older ref rejects with codestale. ctx.ui.updateView(mount, content)replaces the whole content.contenthas the members of a mount withoutkey,slotandtarget. Send every member again,titleincluded: an update without a member clears it.ctx.ui.hideView(mount)andctx.ui.showView(mount)hide and show a mount without ending it.ctx.ui.finishView(mount, result)ends a mount as completed, andresultis any JSON value of at most 65536 bytes.ctx.ui.removeView(mount)ends it as withdrawn. After either, an operation on the mount rejects with codeterminal, and you can mount the same key again.ctx.ui.viewState(key)returns{ mount, state, reason, result }.stateislive,hidden,finished,removedorbroken. The host breaks a mount withreasonsession_replaced,owner_goneorshutdown.ctx.ui.viewDiagnostics(key)returns the notices of a mount: which update the host rejected, which intent it ended, what a client did not draw (undrawn) and why a client did not give the focus (unfocused). The host keeps 32 notices for a mount./reloadloads the extension as a new instance. The mounts of the old instance arebrokenwith reasonowner_gone. The new instance holds no mount and mounts again.
Nodes
A node is a JSON object with a kind. Give a node an id when an intent, an a11y record, a focus record or a drawing names it. Omit a member that you do not set. A kind that no attached client lists in abilities.nodes rejects the mount with code invalid, and so does an unknown member. The sizes of a node are terminal cells.
Kind | What it is | Members |
vstack, hstack | children in a column or a row | children, gap; a child's stack: { basis, grow, shrink, minSize, maxSize } |
container | children in a column | children |
box | padded children on a background | children, paddingX, paddingY (1 when absent), bg |
text | wrapped text | text, paddingX, paddingY (1 when absent), bg |
truncated-text | one row of text, cut at the width | text |
markdown | rendered markdown | text, defaultTextStyle: { color, bgColor, bold, italic, underline, strikethrough } |
lines | rows that your extension drew, shown verbatim | content (an array of strings) |
spacer | empty rows | lines |
dynamic-border | a horizontal rule | color |
select-list | a list with one highlighted item; the user chooses an item | items: [{ value, label, description }], selectedIndex, maxVisible |
settings-list | settings that step through their values | items: [{ id, label, currentValue, values }] |
input | one line of text; Enter submits | value, placeholder |
editor | several lines of text | value |
mouse-region | a button: a click activates it. It needs a pointer (abilities.input.pointer), which the terminal has only in fullscreen mode, so also give its action a binding | children (an array of one node, for example a text with the label), region: { types: ["press"] } |
scroll-view | one child that scrolls | children (an array of one node), follow: "end" |
grid | a calendar-style grid of equal columns; the user chooses a cell | id (required), columns (1 to 16), head (one label for each column), chipRows (1 to 8, default 3), selected (a cell's value), cells: [{ value, label, mark: "current", dim, color, chips: [{ text, color }], more }] |
image | a photograph or other bitmap. The bytes ride in the view's images list, not in the node | ref (the lowercase hex SHA-256 of the bytes), mimeType (image/png, image/jpeg, image/gif or image/webp), maxWidthCells (60 when absent), maxHeightCells, imageId (the Kitty image id of the transmission; absent, the host allocates one; a terminal that draws the image with placeholder cells allocates its own and ignores it), filename, fallbackColor (a theme token); the view carries images: [{ ref, mimeType, data }] with data in base64 |
A grid has at most 128 cells in at most 32 rows, and a cell has at most 8 chips. A cell without a value cannot be chosen. more counts the events that you left out. A bg, a color and the colors of a defaultTextStyle name theme tokens (Themes); a grid color is a theme token, #rrggbb or #rrggbbaa.
A photograph or any other bitmap belongs in an image node. The pixels and shapes drawing profiles (Drawings) are for drawings that your extension computes. The terminal draws no drawing profile, and it draws an image node.
The bytes of an image are not text: they count in the snapshot bytes of the mount and not in its text bytes. The terminal's 262144 snapshot bytes hold a photograph of about 195,000 bytes. The ref is the SHA-256 of the bytes. The terminal declares abilities.imageFormats as ["png", "jpeg", "gif", "webp"]. Pi has no mount view; this node is the D107 view kit's image node (Pi's Image component) under D614.
// week.mjs: a grid, and a view that the user hides and opens again.
export default function week(pi) {
const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
let picked = "Wed";
let mount = null;
const content = () => ({
title: "Week",
view: {
root: {
kind: "grid",
id: "days",
columns: 7,
head: days,
selected: picked,
cells: days.map((day, i) => ({ value: day, label: String(i + 10), mark: day === "Wed" ? "current" : undefined, chips: day === "Fri" ? [{ text: "Demo", color: "#3366ff" }] : [] })),
},
},
intents: [
{ name: "week.pick", nodeKey: "days", arg: { type: "object", properties: { value: { type: "string" } }, required: ["value"] } },
{ name: "week.hide", arg: { type: "object" } },
{ name: "week.open", arg: { type: "object" }, whenHidden: true },
],
bindings: [{ key: "h", intent: "week.hide", name: "Hide" }],
focus: [{ node: "days", request: "mount" }],
});
const show = async (abilities, ctx) => {
if (!abilities || mount || !abilities.slots.includes("panel") || !abilities.nodes.includes("grid")) return;
mount = (await ctx.ui.mountView({ key: "week", slot: "panel", ...content() })).mount;
};
pi.onViewAbilities(show);
pi.on("session_start", (_event, ctx) => show(ctx.ui.viewAbilities(), ctx));
pi.onViewIntent(async (inv, ctx) => {
if (inv.intent === "week.hide") mount = (await ctx.ui.hideView(mount)).mount;
else if (inv.intent === "week.open") mount = (await ctx.ui.showView(mount)).mount;
else {
picked = inv.arg.value;
mount = (await ctx.ui.updateView(mount, content())).mount;
}
return { outcome: "done" };
});
}Intents
An intent is an action that the user raises on a mount. Declare every intent in intents, as the examples do.
nameis unique in the mount. Write it as<extension>.<verb>.nodeKeybinds the intent to the node with thatid. Choosing aselect-listitem or agridcell, changing asettings-listvalue, submitting aninputor aneditor, and clicking amouse-regionraise the intent. The host refuses an intent that has anodeKeywhen a client raises it on another node or on none.- An intent without
nodeKeybelongs to the whole mount. A binding, a drawing region andwhenHiddenneed such an intent. argis the shape of the argument. The host checks the argument against it before your handler runs. Declare an object with a stringvaluefor aselect-list(the item'svalue), agrid(the cell'svalue), aninputand aneditor(the text). Declare an object with stringsitemandvaluefor asettings-list(the setting'sidand its new value). Declare{ type: "object" }for amouse-region: it accepts only{}.- A shape is
{ type }, wheretypeisboolean,string,integer,number,enum(withenum: an array of at most 32 strings),object(withpropertiesandrequired; at most 32 properties, and the value may hold no other property) orarray(withitemsandmaxItems; at most 64 items). A shape nests at most 4 deep. answeris the optional shape of the handler's answer. An answer outside it settles the intentfailed.timeoutMsis 100 to 300000 and defaults to 30000.cancellable: truelets the host abortinv.signalat the timeout.dismiss: truenames the intent that a client raises, with{}, when the user dismisses adialogoroverlaymount, for example with Escape. Your handler closes the mount. At most one intent of a mount has it. It has nonodeKey, and itsargaccepts{}. Without one, the mount stays open until your own key or node closes it. In another slot the member has no effect.whenHidden: truelets a client raise the intent while the mount is hidden. A client lists the hidden mount by its title, and when the user chooses it your handler shows the mount. At most one intent of a mount has it. It has nonodeKey, and itsargaccepts{}.
One handler answers every intent: pi.onViewIntent(async (inv, ctx) => ...). inv has intent, arg, nodeKey, mount, rev, ticket and signal. Return { outcome: "done", answer }, { outcome: "refused", error } or { outcome: "failed", error }. Change your state, call ctx.ui.updateView through the handler's ctx with the ref that you keep, wait for it, then answer. The client is sent the new view before it is told that the intent is done. A hide, a show, a finish and a remove in the handler are also part of the answer. An update from outside the handler while it answers settles the intent stale.
Bindings
bindings (at most 32) ties a key or a gesture to an intent without nodeKey: { key, intent, arg, name } or { gesture, intent, arg, name }.
keyis a key id such asd,shift+leftorctrl+shift+p.gestureisswipe-left,swipe-right,swipe-uporswipe-down. A key or a gesture is bound once.argis the constant argument ({}when absent), so several bindings can raise one intent with different arguments.nameis the label that a client shows.- A binding works only while the mount holds the focus, and after the focused node had the key. An
inputor aneditortakes every key, so give such a view another way to its actions. - The keys
escape,tab,f6andctrlwithc,dorzare reserved: a binding of one rejects with codeinvalid. - A client that does not honour a binding leaves an
unsupportednotice with the pathbindings[i].
Alternatives
A client states facts about itself as claims. alternatives (at most 8) gives a client another view when its claims match. The host sends each client the first alternative whose when holds, otherwise view. One mount and one state serve every client.
Client | Claims |
| terminal | client.kind = "terminal", size.columns (integer), size.rows (integer; the rows of the mount's slot) |
| reference web page | client.kind = "web" |
when is { any: [{ all: [clause, ...] }, ...] }: it holds when every clause of one group holds. A when has at most 8 groups of 8 clauses. A clause is { claim, op, value }, and op is one of:
present: the client states the claim. It takes novalue.equals: the claim equalsvalue, a boolean, an integer or a string.contains: the claimed list holds every string of the arrayvalue.atLeast: the claimed integer is at leastvalue.
const wideTerminal = { any: [{ all: [{ claim: "client.kind", op: "equals", value: "terminal" }, { claim: "size.columns", op: "atLeast", value: 100 }] }] };An alternative is { when, view, drawing }. It shares the mount's intents, bindings, a11y and focus, so use the same node ids in every view. A client is sent the a11y and focus entries of the nodes that its view has. The mount's drawing belongs to view: an alternative does not inherit it.
Accessibility and focus
a11y: [{ node, name, description, role, selected, checked, expanded, busy, disabled, readOnly, required, invalid, relations }]describes the node with idnode. Onlynodeis required.roleis one ofalert,button,checkbox,dialog,group,heading,image,link,list,listitem,menu,menuitem,progressbar,radio,region,status,switch,tab,tablist,tabpanel,textbox,toolbar,treeandtreeitem. A relation is{ kind, target }withlabelledBy,describedBy,controlsorowns.focus: [{ node, request }]makes nodes focusable. The order of the entries is the focus order.request: "mount"asks for the focus when the mount is first drawn.request: "update"asks when the revision that carries it is first drawn, so send it only with the update that moves the focus. At most one entry requests the focus. The client decides: when it does not give the focus, it leaves anunfocusednotice.- Each list has at most 256 entries. A
nodethat no view of the mount has rejects the mount with codeinvalid.
Drawings
A drawing adds vector shapes or a pixel grid to a view. Send a drawing only when abilities.drawing.profiles lists its profile: without a client that draws the profile, the mount rejects with code unsupported.
// meter.mjs: a level meter. A client that draws the scene profile is sent a drawing. Every other client is sent text.
export default function meter(pi) {
let level = 3;
let mount = null;
let scene = false;
const drawing = () => ({
profile: "scene",
node: "canvas",
viewport: { x: 0, y: 0, width: 100, height: 20, fit: "contain" },
shapes: [
{ kind: "rect", x: 0, y: 0, width: 100, height: 20, radius: 4, fill: "#20242c" },
{ kind: "rect", key: "bar", x: 0, y: 0, width: level * 10, height: 20, radius: 4, fill: "accent" },
{ kind: "text", x: 50, y: 14, size: 10, align: "center", text: `${level * 10}%`, fill: "#ffffff" },
],
regions: [{ key: "raise", shape: { kind: "rect", x: 0, y: 0, width: 100, height: 20 }, gestures: ["activate"], intent: "meter.raise", name: "Raise the level" }],
});
const text = () => ({ kind: "text", text: `Level ${level} of 10. Press r to raise it.` });
// The region and the binding raise the intent, so the intent has no nodeKey.
const content = () => ({
view: { root: scene ? { kind: "box", id: "canvas" } : text() },
...(scene ? { drawing: drawing() } : {}),
intents: [{ name: "meter.raise", arg: { type: "object" }, answer: { type: "object", properties: { level: { type: "integer" } }, required: ["level"] } }],
bindings: [{ key: "r", intent: "meter.raise", name: "Raise" }],
fallback: text(),
});
const show = async (abilities, ctx) => {
if (!abilities || mount || !abilities.slots.includes("panel")) return;
scene = abilities.drawing?.profiles.includes("scene") ?? false;
try {
mount = (await ctx.ui.mountView({ key: "meter", slot: "panel", ...content() })).mount;
} catch (err) {
ctx.ui.notify(`meter: ${err.code ?? err.message}`, "error");
}
};
pi.onViewAbilities(show);
pi.on("session_start", (_event, ctx) => show(ctx.ui.viewAbilities(), ctx));
pi.onViewIntent(async (inv, ctx) => {
if (inv.intent !== "meter.raise") return { outcome: "refused", error: "unknown intent" };
level = Math.min(10, level + 1);
mount = (await ctx.ui.updateView(mount, content())).mount;
return { outcome: "done", answer: { level } };
});
}profileisscene(vectorshapes) orpixels(pixels: { width, height, asset, scaling: "nearest" | "smooth" }over an image asset declared inassets).nodeis the id of the view node that the drawing fills. Withoutnode, the drawing follows the view.viewportis optional:{ x, y, width, height, fit }is the rectangle of drawing coordinates that the client shows.widthandheightare positive, andfitiscontain,coverorstretch.- A shape has a
kindand the members of that kind. A member of another kind rejects the drawing.
Shape | Members |
rect | x, y, width, height, radius (optional) |
ellipse | cx, cy, rx, ry |
line | x1, y1, x2, y2 |
polyline | points: [{ x, y }] (2 to 1024), closed |
path | commands: [{ op, ... }] (1 to 1024, the first is move); op is move or line (x, y), quad (x1, y1, x, y), cubic (x1, y1, x2, y2, x, y) or close |
text | x, y, text, size, align: "start" | "center" | "end" |
image | x, y, width, height, asset |
group | children |
- Every shape also takes the optional
key,fill,stroke: { color, width },opacityandtransform(six numbers). A color is#rrggbb,#rrggbbaaor a theme color token. regions: [{ key, shape, gestures, intent, name, role }]turns a gesture insideshapeinto a declared intent.keyis unique among the regions.shapeis arect, anellipseor a closedpolyline.gestureslistsactivate,press,releaseordrag.nameis required, androleis optional. The client tests which region a pointer is in, and it raises the intent with an argument of the intent'sargshape. Declare a region's intent withoutnodeKey.- A client fills the argument from the intent's
argshape and sets only the properties that shape names:xandy(the pointer in the drawing's coordinates; for anactivatemade with the keyboard, the centre of the region),dxanddy(fordrag, the movement since the last event of that drag; 0 for every other gesture),gesture(activate,press,releaseordrag) andregion(the region'skey). A shape that names none of them is sent{}, and a property of typeintegertakes the nearest whole number. Only the reference web page (examples/ui-view-web, which runs with Node and is not part of the pig binary) raises the gesture of a region of a drawing. The terminal view client draws no drawings, so it raises none, and nothing else in this repository does. - A client raises a region's
activatefor a click, and a web page also raises it when Enter or Space reaches the focused region. The web page puts thatactivateat the centre of the region's shape, and its argument carries no mark that tells it from a click. Keep a separate button for the default action, or give the region a shape whose centre is a place you can act on. - A drawing has at most 4096 shapes nested 8 deep, 1048576 pixels and 64 regions, and never more shapes or pixels than
abilities.drawing.shapesandabilities.drawing.pixels(codelimit).
Slots
slot is one of notify, status, widget-above, widget-below, header, footer, dialog, overlay, panel, tool-card, message and entry. A mount has one slot. To show the same state in a panel and in a dialog, make two mounts with two keys. Mount only in a slot that abilities.slots lists: another slot rejects with code unsupported.
A mount in the slot dialog is a dialog over the screen, as todo.mjs shows. Give it a title. Only your extension closes a dialog: hide, finish or remove the mount in a handler. Declare one intent with dismiss: true for the user's Escape or close control, and also bind a key with a name, because a client that does not raise the dismiss intent leaves the mount open. escape cannot be bound.
Errors
A rejected operation rejects its promise with an Error whose code is one of:
Code | Meaning |
invalid | The record is malformed or past a bound of the host: an unknown member, node kind, slot or operator, a key that is already mounted, or a list that is too long. Nothing changes. |
unsupported | No attached client can draw the mount: no client is attached, no client draws the slot or the drawing profile, or the mount declares intents and the client delivers no input. |
limit | The content exceeds what the client states in abilities.limits (nodes, depth, snapshotBytes, textBytes, mounts) or in abilities.drawing. |
stale | The ref is not the newest ref of the mount. |
terminal | The mount has ended. |
not_found | The extension has no mount under this key. |
The calls in each SDK
Every SDK has every call, and its mount takes the same members. The Go, Python, Rust and Lisp SDKs build the view with their component kit.
Call | Node | Go | Python and Rust | Lisp |
| read the abilities | ctx.ui.viewAbilities() | ctx.ViewAbilities() | ctx.view_abilities() | ctx-view-abilities |
| abilities changed | pi.onViewAbilities | ext.OnViewAbilities | ext.on_view_abilities | on-view-abilities |
| mount | ctx.ui.mountView | ctx.MountView | ctx.mount_view | ctx-mount-view |
| update | ctx.ui.updateView | ctx.UpdateView | ctx.update_view | ctx-update-view |
| hide, show | hideView, showView | HideView, ShowView | hide_view, show_view | ctx-hide-view, ctx-show-view |
| finish | finishView(mount, result) | FinishView, FinishViewWith | Python finish_view(mount, result=...); Rust finish_view, finish_view_with | ctx-finish-view (:result) |
| remove | removeView | RemoveView | remove_view | ctx-remove-view |
| state | viewState | ViewState | view_state | ctx-view-state |
| diagnostics | viewDiagnostics | ViewDiagnostics | view_diagnostics | ctx-view-diagnostics |
| answer intents | pi.onViewIntent | ext.OnViewIntent | ext.on_view_intent | on-view-intent |
Every SDK builds the image node. Go: kit.NewImage(data, mimeType). Rust: kit::Image::new(data, mime_type), with max_width_cells, max_height_cells, image_id, filename and fallback_color as builder methods. Python: kit.Image(data, mime_type, max_width_cells=..., max_height_cells=..., image_id=..., filename=..., fallback_color=...). Lisp: kit-image (data mime-type &key max-width-cells max-height-cells image-id filename fallback-color id). Node: write the { kind: "image", ref, mimeType } node as JSON and the bytes in images: [{ ref, mimeType, data }] of the view. A ctx.ui.custom component of a Node extension may use Pi's own Image component instead.
What the clients draw
Capability | Terminal ( viewClient: terminal) | Reference web page ( examples/ui-view-web) |
| Slots | widget-above and widget-below (at most 10 rows each), panel (at most half the terminal's rows), dialog; every other slot is not drawn at this version | all twelve slots, each in its own section of the page |
dialog | a titled frame centred over the screen, eight tenths of the terminal's columns and rows; its size.columns and size.rows claims are the cells inside the frame. It takes the keys when it is shown, unless the user types in the editor: then it waits as one row above the editor (<title>: F6 to enter) and leaves an unfocused notice. Escape returns the keys to the editor, and the mount stays live; with a dismiss intent, the first Escape raises it instead. Several dialogs stack, the last on top. A hidden dialog is not listed | drawn in its section of the page, like every other slot |
| Node kinds | every kind of Nodes | every kind of Nodes |
| Image node | drawn from png, jpeg, gif and webp bytes, at most as tall as the slot's rows. In kitty and Ghostty: one Kitty transmission, then placeholder cells that scroll and erase like text. In another Kitty terminal and in iTerm2: the image in its rows. Without an image protocol (tmux, a plain terminal): half-block cells. Bytes that cannot be decoded: one line of text with the file name, the type and the size | drawn as an image |
| Limits of one mount | 512 nodes, depth 16, 262144 snapshot bytes, 65536 text bytes, 16 mounts, 4096 intent argument bytes | 2048 nodes, depth 32, 4194304 snapshot bytes, 65536 text bytes, 32 mounts, 65536 intent argument bytes |
title | panels are tabs, labelled by title, or by key without one; a dialog frame carries it | the heading of the mount, and the label of a panel's tab, or key without one |
Intents with nodeKey | raised by the keys and clicks of the node | raised by the keys and clicks of the node |
Intents without nodeKey | raised by a binding only, apart from the whenHidden and dismiss intents of the rows below; for any other the plugin gets a notice that the terminal offers no control | a button in the mount's header, labelled with the intent's verb in words and titled with its name, unless a binding, a region of a drawing or whenHidden raises the intent |
bindings | keys work in a focused panel or dialog, and the named bindings are listed under it; gestures are not offered, and the plugin gets an unsupported notice | key bindings fire while the focus is in the mount, and a named one is also a button that shows its key; swipes are not offered, and the plugin gets an unsupported notice |
Hidden mount with whenHidden | a dim tab; Enter raises the intent | a button that reads the mount's title, in the list of hidden views above the prompt |
dismiss intent | raised with {} by Escape in a focused dialog; a second Escape returns the keys to the editor | raised with {} by Escape in a dialog or overlay mount |
| Focus | F6 walks from the editor through the tabs and back, Escape returns to the editor; a focus record that requests it moves the keys to its node | the focus order is the tab order, and a changed focus record moves the focus to its node |
a11y | not used at this version | name, description, role, the states and the relations become ARIA attributes |
| Drawings | not drawn at this version: the terminal states no drawing profile | drawn: the scene and pixels profiles, with each region of a drawing as a focusable element that takes the pointer and the keyboard |
Terminal UI lists the terminal's rows and keys. Piglets describes viewClient and viewEndpoint.