Wire Protocol¶
The Python package is one client of nib-runtime. The runtime is a Swift
process that owns the menu bar item, the popover and every native control; it
knows nothing about Python. What it speaks is a small protocol over a Unix
socket, so an SDK in Rust, Go, Swift or anything else is a client of the same
protocol. This guide is the contract such an SDK has to honour, drawn from
the Python implementation and the runtime source.
Read it top to bottom once. The last section is a checklist.
The split¶
| Side | Owns | Never does |
|---|---|---|
| SDK (your language) | the view tree as data, event handlers, app state, diffing, services calls | drawing, layout, native APIs |
Runtime (nib-runtime) |
SwiftUI rendering, the popover and settings windows, the context menu, hotkeys, notifications, services | application logic, state |
The SDK describes the interface as a tree of nodes and sends it. The runtime renders it and reports what the user did as events. The SDK runs the handler, mutates its own tree, diffs it and sends only what changed. Everything else in nib, hot reload, settings persistence, services, is built on those three messages.
Process model¶
The two processes are started one of two ways.
Development, and any non-Python bundle. The SDK launches the runtime and
waits for its socket. The runtime binary is nib-runtime, universal, built with
make build-runtime; the Python wheel ships it at nib/bin/nib-runtime, and a
Rust crate would ship it the same way. The environment it reads:
| Variable | Meaning |
|---|---|
NIB_SOCKET |
Path of the Unix socket to listen on. The SDK chooses it, /tmp/nib-<pid>.sock in Python |
NIB_PARENT_PID |
Your process id. The runtime exits when that process dies, so a crash never leaves an orphaned menu bar icon |
NIB_BUNDLE_ID |
Reverse DNS identifier, the UserDefaults domain and the name of the log file |
NIB_LOG_FILE |
Log file both processes append to, /tmp/nib-<identifier>.log by default |
NIB_LOG_LEVEL |
debug to see every message on the runtime side |
Give the runtime its own session (setsid) so a Ctrl-C in the terminal
reaches your process only; you then send quit and the runtime leaves in
order. Connect with retries: the socket appears a few tens of milliseconds
after launch.
A built .app. A bundle made by nib build has the runtime as the main
executable; it detects an embedded Python at
Contents/Resources/python/bin/python3 and spawns it. That path is Python
specific. For another language the simplest layout is the mirror image: your
compiled binary is the main executable in Contents/MacOS, nib-runtime sits
next to it, and your binary launches it exactly as in development. The runtime
sees no embedded Python and runs in development mode, which is what you want.
Info.plist needs LSUIElement true for a menu bar only app; the keys
nib build writes are a good template, see build_plist_dict in
sdk/python/nib/cli/build.py.
Transport¶
- Unix domain stream socket. The runtime is the server, the SDK the only client; a second connection replaces the first.
- Every message is a MessagePack map, framed by a 4 byte big endian length prefix. Nothing else is on the wire, no newline, no magic bytes.
- Both sides refuse a frame larger than 256 MB, and the runtime drops the
client that sent one. Send images as
bin, not base64 strings. - Writes must be serialised. One lock around "write length, write body" is enough; pack outside it so a large render does not block other senders.
- Read on a dedicated thread. Accumulate bytes, pull complete frames, decode, dispatch. Never run user code on that thread: a handler that makes a blocking service call would wait on the very thread meant to deliver its reply. Python queues events to a second thread and runs handlers there, one at a time, so handlers never run concurrently either.
Strings are UTF-8 and MessagePack str. Numbers keep their type: the runtime
decodes a float field from int and the reverse, but booleans must be
MessagePack bool, not integers.
Handshake¶
There is no hello message. The first flatRender carries protocolVersion;
the runtime compares it with the version baked into its schema and logs a
warning on mismatch. The current version is 8, defined in
sdk/python/nib/core/protocol.py; keep a constant for it and bump it with
the Python SDK, since the runtime is shared.
Query the binary before launch with nib-runtime --version if you want to
refuse an old runtime early.
Messages the SDK sends¶
Every message is {"type": <string>, "payload": <map>} except quit, which
has no payload.
type |
Payload | Purpose |
|---|---|---|
flatRender |
nodes, rootId, statusBar, window, menu, hotkeys, fonts, protocolVersion |
Replace the whole interface and the app chrome |
patch |
patches: list of operations |
Update nodes in place |
quit |
none | Ask the runtime to exit |
notification |
action, requestId, notification, notificationId, trigger |
Notifications: push, schedule, cancel, query, permission. A one-line notification is a push |
clipboard |
action (read or write), content, requestId |
Clipboard access; a read answers with an event |
fileDialog |
action (pickFiles, pickDirectory, saveFile), requestId, dialog options |
Open and save panels |
userDefaults |
action (get, set, remove, clear, containsKey, getKeys), key, value, prefix, requestId |
Persistent settings. value is a native MessagePack value: string, number, bool, list or map |
service |
service, action, requestId, params |
Battery, connectivity, screen, keychain, camera, launch at login, permissions, applescript, workspace, vision, language, speech, sound, files, pdf, spotlight, shortcuts, quicklook, audio, maps |
action |
nodeId, action, params |
Imperative call on a view, for example reload on a WebView |
settingsRender |
title, width, height, tabs |
Define the settings window |
settingsOpen, settingsClose |
empty map | Show or hide it |
flatRender in full, with the fields the Python SDK fills:
{
"type": "flatRender",
"payload": {
"nodes": [...], # see The node model
"rootId": "0",
"statusBar": {"icon": icon, "title": "My App"},
"window": {"width": 300.0, "height": 200.0, "floatOnTop": False},
"menu": [...], # context menu items, or None
"hotkeys": ["cmd+shift+n"], # [] when none are registered
"fonts": {"Iosevka": "fonts/Iosevka-Regular.ttf"}, # or None
"protocolVersion": 8,
},
}
icon is an SF Symbol name, a map {"name", "weight", "scale",
"renderingMode", "color"}, or {"view": <node>} for a view used as the icon. A menu item is
{"id", "title", "icon", "divider": false, "shortcut", "badge", "state",
"enabled", "children", "content", "height"}; a divider is
{"id", "divider": true}. Item ids are strings you choose; the runtime echoes
them in menu:tap events. content is a nested node, the only place the
protocol still uses the nested shape.
A patch is a list of operations, each with the node id:
op |
Fields | When |
|---|---|---|
props |
props: the node's complete new props map |
Any prop changed |
modifiers |
modifiers: the complete new list |
Any modifier changed |
canvasAppend |
commands: the draw commands added since the last frame |
A Canvas grew without being cleared; cheaper than resending the whole list |
children |
childIds: the node's complete new child list, in order; nodes: the flat nodes the runtime has not seen, with their subtrees |
A child was added, removed or reordered; a hidden view shown |
chrome |
id is "_app"; any of statusBar, window, menu, hotkeys, fonts, each sent whole when it changed |
The title, icon, window, menu, hotkeys or fonts changed |
props, modifiers and canvasAppend apply to nodes the runtime has. A
children op picks the new child list from the node's current children and
from nodes; children no longer listed are dropped. A node that changes type
or moves to another parent needs a full flatRender.
Messages the runtime sends¶
type |
Fields | Meaning |
|---|---|---|
event |
nodeId, event, value |
The user did something, or a request answered through an event |
serviceResponse |
service, requestId, data |
Answer to a service query |
notificationResponse |
requestId, data |
Answer to a notification message, and action clicks |
fileDialogResponse |
requestId, cancelled, files, directories, saveResult |
Answer to a fileDialog message; files is a list of maps with the path and file details |
error |
message, context |
The runtime could not do what it was asked |
event is the one to get right. event is a kind token, never data, and
value carries the payload with its MessagePack type intact, or is absent.
A view event is a bare kind on the view's node id (pan:* and webview:*
belong to the view too); every other event is <scope>:<kind> on the
scope's own id.
event |
nodeId |
value |
|---|---|---|
tap |
the Button | none |
click |
a view with an on_click |
none |
menu:tap |
the menu item id | none |
change |
TextField, Toggle, Slider, Picker, TextEditor... | the new value: string, bool, float |
submit |
TextField | the text |
expand, navigate, selection, sort |
the owning view | view specific |
region |
the Map | the visible region after the user moved the map |
mouseMove, pan:start, pan:update, pan:end |
the Canvas | [x, y] as floats |
drop |
the drop target | list of file paths |
hotkey:pressed |
"hotkey" |
the shortcut string |
hotkey:unavailable |
"hotkey" |
none; Accessibility access is missing |
action:unhandled |
the view | the action name: no view registered a handler for an action message |
clipboard:read |
the requestId of the read |
the text |
userDefaults:<action> |
the requestId |
the result, as a native value; only get, containsKey and getKeys answer, and userDefaults:error reports a failure |
app:appear, app:disappear |
"_app" |
none; the popover opened or closed |
system:<name> |
"_app" |
sleep, wake, screen_lock, screen_unlock, displays carry none; appearance carries dark as bool |
For controls the runtime owns state for, text fields, toggles, sliders,
pickers, apply the change value to your own copy of the node before calling
the handler, so a handler that reads the field sees what is on screen, and so
the next diff does not send the old value back.
serviceResponse.data has the same shape for every service: success, and
either result, the answer (a value, a list or a map whose keys the service
documents), or errorMessage, the runtime's reason. unsupported: true
marks a service or action the runtime does not know. Correlate by
requestId, time out after ten seconds, and fail every pending request when
the socket drops.
The files service also sends files:change events whose nodeId is the
watch id it returned and whose value is a list of {path, kinds,
isDirectory}; stop the watch with unwatch. The camera service sends a
running stream's frames as serviceResponse messages with isStreamFrame:
true and the frame map in result, under the startStream request id.
The applescript service takes run with params.source, and call with
source, handler and args, a list of plain values passed to the handler.
Its answer carries result, the script's value as native MessagePack, and on
failure errorNumber next to errorMessage. Scripts can be slow: give these
requests a longer timeout than the other services.
The node model¶
A node is a map with these keys. The tree is sent flat, one node per entry, linked by ids, so the runtime rebuilds it without recursion.
| Key | Type | Notes |
|---|---|---|
id |
string | Stable identity, see below |
type |
string | One of the known view types, for example VStack, Text, Button, Canvas, LineMark |
props |
map | View specific, keys per the schema |
modifiers |
list or absent | [{"type": "frame", "args": {"width": 100.0}}, {"type": "padding", "args": {"value": 16.0}}] |
parentId |
string or absent | absent on the root |
childIds |
list or absent | in order |
backgroundId, overlayId |
string or absent | a node rendered behind or over this one |
contextMenuIds |
list or absent | nodes of a per-view context menu |
slot |
string or absent | role of a child in its parent, for example title and icon in a Label, or a navigation route |
animationContext |
map or absent | the animation a property change on this node uses |
Ids are paths: the root is "0", its children "0.0", "0.1", a grandchild
"0.1.2". The id is how the runtime names a node in events and how a patch
targets it, so the same view must keep the same id across renders. Position
based paths give you that for free as long as the tree shape is stable, and
a shape change is a full render anyway. Chart marks are nodes too, with
modifiers absent, as children of their Chart.
Props hold plain values: strings, numbers, booleans, lists, maps. Colours are
hex strings or names, fonts are maps, enums are their string values, images
are MessagePack binary. Whatever your language's type system offers, resolve
it to those before the socket, as Python does in wire.py.
One prop breaks that rule: a Chart's chartData is
{"columnsJson": <JSON string>, "rowCount": <int>}, the data as columns
encoded as JSON text. Build it the way Chart does in
sdk/python/nib/views/charts/chart.py.
The schema is the contract¶
The runtime does not accept arbitrary view types or props. The set it knows is
generated from the Python view classes by scripts/gen_schema.py into
package/Nib/Generated/NibSchema.swift: protocolVersion and
knownViewTypes. The runtime checks the version against it at connect, and a
debug build logs any known view type it has no builder for. Prop names are
not in the generated file: the runtime decodes the props it knows from each
node and ignores the rest.
For a second SDK the Python classes are the source of truth for prop names:
each view's _PROP_FIELDS tuples give the wire name, and the Swift side reads
them in package/Nib/Protocol/ViewNode.swift. The way to do this properly is
to have make gen also emit the view types and their props as JSON, say
schema/nib-schema.json, and generate your language's view types from it:
{
"protocolVersion": 8,
"views": {
"Text": ["content", "textStyles", "attributedStrings"],
"Toggle": ["isOn", "label", "toggleStyles"]
}
}
That is a small change to the generator, and it turns "read the Python" into
"run a code generator", which is how a third SDK should start. Until it
exists, NibSchema.swift is readable by hand and has 49 view types.
Modifiers are not in the schema. The runtime knows these types, listed in
package/Nib/Protocol/ViewModifier.swift, and skips any other one without
failing the render: frame, padding, margin, background,
foregroundColor, fill, stroke, font, cornerRadius, opacity,
clipShape, shadow, border, contentTransition, transition,
blendMode, scale, offset. Animation is not a modifier: it travels in
the node's animationContext. Their args are what
sdk/python/nib/modifiers/ produces; the docstrings there spell out each map.
The runtime applies the list in order, innermost first, so the order is part
of the layout. Send them in the order _APPLIERS in
sdk/python/nib/modifiers/__init__.py uses: font, foregroundColor, fill,
stroke, contentTransition, padding, frame, background, border, cornerRadius,
clipShape, shadow, opacity, blendMode, scale, margin, offset, transition.
Padding then sits inside the frame and the background, and margin and offset
outside everything.
What the SDK has to implement¶
- A view model that can produce the flat node list. Give every view a
type string, a props map and a modifier list, and a traversal that assigns
path ids and collects children, background, overlay and context menu
nodes. Keep the handlers out of the wire data: a Button's
actionis a function you store in a map keyed by the node id. - Rendering and diffing. First render is a
flatRender. After a handler runs, build the new flat list and compare it with the previous one by id. If the ids and types match position for position, emitpropsandmodifiersops for the nodes that differ,canvasAppendwhen a Canvas only gained commands,childrenfor a node whose child list changed (with the new nodes) andchromefor the icon, title, window, menu, hotkeys or fonts. A node that changed type or parent needs a full render. Batch: several property changes inside one handler should produce one message, not one per change. - Event dispatch. A reader thread, a queue, a handler thread. Route by
nodeIdandeventkind. Apply runtime owned state first. Catch every exception in a handler and log it; a raising handler must not stop the loop. - Request and reply. A pending map from
requestIdto a waiter for services, user defaults, clipboard reads, file dialogs and notification queries. Generate ids with a UUID. Resolve from the reader thread, never block on it. - Lifecycle. Launch, connect with retries, send the first render, run
until quit. On the socket dropping, stop the handler loop, fail pending
requests and tell the app; the runtime going away is otherwise silent.
Send
quiton a clean exit and wait briefly for the process. - Logging to the shared file in the same line format if you can; one interleaved log is how a crash on either side gets diagnosed.
A minimal client¶
Enough to see a popover with a title and a button, in a language neutral sketch. Replace the pseudo calls with your socket and MessagePack library.
socket = "/tmp/nib-" + pid + ".sock"
spawn("nib-runtime", env = {NIB_SOCKET: socket, NIB_PARENT_PID: pid,
NIB_BUNDLE_ID: "com.example.hello"})
conn = connect_with_retries(socket)
nodes = [
{id: "0", type: "VStack", props: {spacing: 8.0},
childIds: ["0.0", "0.1"],
modifiers: [{type: "padding", args: {value: 16.0}}]},
{id: "0.0", type: "Text", props: {content: "Hello"}, parentId: "0"},
{id: "0.1", type: "Button", props: {label: "Tap me"}, parentId: "0"},
]
send(conn, {type: "flatRender", payload: {
nodes: nodes, rootId: "0",
statusBar: {icon: "hand.wave", title: "Hello"},
window: {floatOnTop: false}, protocolVersion: 8}})
loop:
msg = read_frame(conn)
if msg.type == "event" and msg.nodeId == "0.1" and msg.event == "tap":
nodes[1].props.content = "Tapped"
send(conn, {type: "patch", payload: {patches: [
{op: "props", id: "0.0", props: {content: "Tapped"}}]}})
send packs the map, writes the 4 byte big endian length, then the bytes.
read_frame does the reverse. With that much working, every other feature is
another message type from the tables above.
In Rust the natural pieces are std::os::unix::net::UnixStream, rmp-serde
for MessagePack with serde structs for the messages, a std::thread reader
feeding a channel, and std::process::Command with .env() and a
pre_exec calling setsid for the runtime.
Testing against the real runtime¶
Unit tests can fake the socket, as Python's tests/conftest.py does with a
FakeConnection that records every message. The runtime itself is the only
judge of the wire format, so keep one end to end check: start the real
nib-runtime with NIB_LOG_LEVEL=debug, drive one value of each MessagePack
type through a patch, and grep the log for the runtime's own failure lines.
scripts/smoke.py does exactly that for Python and is the model; the lines
the runtime writes when it drops something are:
Unknown view type, Schema drift, Ignoring unknown,
Failed to (pack|encode|process)
That check caught a bug once where every non-integer prop was decoded as an empty array; nothing on the SDK side could have seen it.
Checklist¶
- [ ]
PROTOCOL_VERSIONconstant, sent in everyflatRender, bumped with the Python SDK - [ ] View types and prop names generated from the schema, not typed by hand
- [ ] 4 byte big endian length framing, MessagePack maps,
binfor bytes - [ ] Reader thread, serialised handler thread, write lock
- [ ] Path ids, flat node list, full render then patches
- [ ] Runtime owned state applied before handlers
- [ ]
requestIdcorrelation with timeouts and failure on disconnect - [ ] Launch with
NIB_SOCKET,NIB_PARENT_PID,NIB_BUNDLE_ID,NIB_LOG_FILE; own session;quiton exit - [ ] Ship
nib-runtimewith the package and check--version - [ ] One smoke test against the real runtime
Related¶
- Architecture: the two processes and the messages between them
- Reactivity: how the Python SDK diffs the tree into patches
- App events: the
system:<name>events in practice - Assets and Fonts: what
fontsin aflatRenderpoints at