# UI Protocol
**Status:** Definition only — transport-agnostic specification. Transport bindings (stdin/stdout, WebSocket, in-process) are future appendices; this document defines only the message format, the rules both sides follow, and the full message taxonomy with examples.
**Scope:** This document defines how any User Interface (a terminal app today, a web app later) talks to the PaperOS core. It does not change terminal behavior, does not implement an event bus in core, does not add dependencies, and does not pick a concrete transport. Concrete wire framing is deferred to transport appendices named below.
---
## Introduction
PaperOS follows a *minimal core + extensions* architecture (see `docs/architecture.md`). The core provides the runtime, command routing, and event bus; extensions provide commands, actors, views, and I/O.
The UI protocol is the contract between the UI bridge and any UI client. It is a **message-based** protocol:
- The UI is a **projection** — it renders state pushed from the core and sends commands/actions back. (architecture.md §18)
- The **same core** supports Web UI, Desktop WebView, Terminal, and Remote Web UI. The core does not know which UI connects. (architecture.md §20)
- The protocol is **transport-agnostic** — it works over a pipe, a TCP connection with WebSocket framing, or an in-process channel. Only the framing of individual messages (how bytes are split into messages) is transport-specific; the message shapes are not.
- Messages are **JSON** — the project already uses `serde`/`serde_json`, and any future web UI can natively parse it.
### Message taxonomy
```text
UI → Core (requests — client-initiated, expect a correlated reply or event)
hello handshake / version negotiation
command invoke a named command (mirrors run_command)
input keyboard / text input
focus view gained keyboard focus
resize terminal / viewport resize
view.action view-specific action
view.subscribe subscribe to state updates for a view
view.unsubscribe stop receiving updates for a view
Core → UI (responses / unsolicited updates)
reply result of a request
error error reply (machine-readable code + message)
event state-change event (see §10 catalog)
state full state snapshot for a view
notification unsolicited human-facing message
layout view tree arrangement (see §33)
```
(architecture.md §19–20)
### How to read this document
Each message in sections 3–5 has: a purpose paragraph, a JSON schema, and one or more ```json examples. Every ```json block is a complete envelope message. The acceptance test (`tests/acceptance/ui_protocol_tests.rs`) parses every fenced example and enforces envelope invariants, so the document is machine-checked.
---
## Envelope
This protocol uses **JSON Lines framing**: each message is a single complete JSON object on one line. There are no interior newlines within a payload (string values are escaped via standard JSON string escaping). Each line is independently parseable.
```text
{"v":1,"id":"req-1","type":"hello","payload":{"version":1}}
{"v":1,"seq":1,"type":"reply","id":"req-1","payload":{"ok":true,"result":{"version":1}}}
```
### Envelope fields
| `v` | integer | Both | Yes | Protocol version (see versioning policy, §6). |
| `id` | string | UI → Core (req) | Yes (req)| Client-side unique identifier for request/reply correlation. The server echoes this in the matching `reply` or `error`. |
| `seq` | integer | Core → UI | Yes (resp)| Monotonic-per-connection sequence number for Core→UI messages, starting at 1. Used for ordering on the client. Absent on UI→Core messages. |
| `type` | string | Both | Yes | Message type — one of the catalog values in sections 3–5. |
| `payload`| object | Both | Yes | Structured body of the message. Always a JSON object (possibly empty). |
### Request vs. response
- **UI → Core** messages (section 3 catalog) MUST include `id` and MUST NOT include `seq`.
- **Core → UI** messages (section 4 catalog) MUST include `seq`. The `reply` and `error` types MUST also include `id` (echoing the request they answer). `event`, `state`, `notification`, and `layout` are unsolicited and may omit `id`.
```json
{"v":1,"id":"h-001","type":"hello","payload":{"version":1}}
```
### Transport properties
The byte stream carrying JSON Lines MUST be:
- **Bidirectional** — both sides can send.
- **Ordered** — messages arrive in the order sent on a given direction.
- **Reliable** — no message loss (TCP semantics).
- **Message-boundary preserving** — the transport preserves line/message boundaries so the receiver can split on `\n`.
Transport bindings (named for future appendices — NOT specified here):
- `stdin/stdout` — newline-delimited JSON over the process stdio pipe.
- `WebSocket` — one text frame per JSON line, `ws://<host>:4017/ws`.
- `in-process` — direct channel send, no framing needed.
### Version negotiation
The protocol version is an integer in the `v` envelope field. The client declares its highest supported version in the `hello` payload (`version` field). The server replies with the negotiated version (the minimum of what both sides support). A major-version mismatch terminates the session with an `unsupported_version` error (§6).
```json
{"v":1,"id":"h-001","type":"hello","payload":{"version":1}}
```
---
## Session
### Hello / version handshake
When a connection is established, the client MUST send `hello` as its first message. The server responds with `reply` (echoing the `id`) containing the negotiated version, or `error` with code `unsupported_version` if the client's requested version is incompatible.
```json
{"v":1,"id":"h-001","type":"hello","payload":{"version":1}}
```
```json
{"v":1,"seq":1,"type":"reply","id":"h-001","payload":{"ok":true,"result":{"version":1}}}
```
```json
{"v":1,"seq":1,"type":"error","id":"h-001","code":"unsupported_version","payload":{"message":"client version 2 not supported; server supports 1"}}
```
### View subscriptions
The client subscribes to views (see §7 for view addressing and registry) by sending `view.subscribe` with a `view:<id>` target. The server replies with `reply`, then begins pushing `state` snapshots and `event` messages for that view.
```json
{"v":1,"id":"sub-001","type":"view.subscribe","payload":{"view":"view:buffer"}}
```
```json
{"v":1,"seq":2,"type":"reply","id":"sub-001","payload":{"ok":true,"result":null}}
```
Unsubscribing stops state/event delivery for that view:
```json
{"v":1,"id":"unsub-001","type":"view.unsubscribe","payload":{"view":"view:buffer"}}
```
If a client subscribes to an unknown view, the server responds with `error` / `unknown_view`:
```json
{"v":1,"seq":3,"type":"error","id":"sub-002","code":"unknown_view","payload":{"message":"unknown view: view:nonexistent"}}
```
### Disconnect
The client closes the transport stream. The server cleans up all subscriptions and session state for that connection. No explicit logout message is required.
### Reconnection
On disconnect, the server treats each connection as fresh — there is no session continuity in this version. A reconnecting client sends a new `hello` with new `id`s and re-subscribes to the views it wants. The server does not persist subscriptions across disconnects.
---
## UI to Core messages
### hello
**Purpose:** The first message after connection. Negotiates protocol version and announces the client's capabilities.
**Payload fields:**
| `version` | integer | Highest protocol version the client supports. |
```json
{"v":1,"id":"h-001","type":"hello","payload":{"version":1}}
```
### command
**Purpose:** Invokes a named command on the core's command bus. This mirrors `runtime.run_command("name args")` with the `Option<ActorId>` target model (see `src/core/runtime.rs`). The args are split with `splitn(2)` semantics: the first whitespace-delimited token is the command name, the remainder is a single argument string.
**Payload fields:**
| `name` | string | Command name (e.g. `"open"`, `"write"`, `"undo"`). |
| `args` | array[string] | Command arguments. |
| `target` | `"buffer:<id>"` \| `"view:<id>"` \| null | Optional execution target. When targeting a buffer, maps to `Option<ActorId>` in `run_command`. |
```json
{"v":1,"id":"cmd-001","type":"command","payload":{"name":"open","args":["README.md"],"target":null}}
```
```json
{"v":1,"id":"cmd-002","type":"command","payload":{"name":"save","args":["/tmp/example.txt"],"target":"buffer:buf-1"}}
```
### input
**Purpose:** Sends a keyboard or text input event to the core for dispatch to the active input extension (`InputExtension` or `ViInputExtension`).
**Payload fields:**
| `kind` | `"key"` \| `"text"` \| `"ping"` | Input kind. `"key"` for a named key, `"text"` for an inserted character/string, `"ping"` for heartbeat. |
| `value` | string | The key name (e.g. `"arrow_down"`, `"enter"`, `"ctrl-s"`) or text content. |
```json
{"v":1,"id":"in-001","type":"input","payload":{"kind":"text","value":"x"}}
```
```json
{"v":1,"id":"in-002","type":"input","payload":{"kind":"key","value":"arrow_down"}}
```
### focus
**Purpose:** Notifies the core that a view has gained keyboard focus.
**Payload fields:**
| `view` | `"view:<id>"` | The view that received focus. |
```json
{"v":1,"id":"f-001","type":"focus","payload":{"view":"view:buffer"}}
```
### resize
**Purpose:** Notifies the core of a viewport / terminal resize.
**Payload fields:**
| `rows` | integer | New viewport height in rows. |
| `cols` | integer | New viewport width in columns. |
```json
{"v":1,"id":"r-001","type":"resize","payload":{"rows":24,"cols":80}}
```
### view.action
**Purpose:** A view-specific action invocation. The view handles the action via its extension-provided handler.
**Payload fields:**
| `view` | `"view:<id>"` | Target view. |
| `action` | string | Action name. |
| `args` | object | Action arguments (arbitrary JSON object). |
```json
{"v":1,"id":"va-001","type":"view.action","payload":{"view":"view:buffer-list","action":"open","args":{"file":"main.rs"}}}
```
### view.subscribe
**Purpose:** Subscribes to state and event updates for a view. See §2 (Session).
**Payload fields:**
| `view` | `"view:<id>"` | View to subscribe to. |
```json
{"v":1,"id":"sub-001","type":"view.subscribe","payload":{"view":"view:buffer"}}
```
### view.unsubscribe
**Purpose:** Stops receiving state and event updates for a previously-subscribed view.
**Payload fields:**
| `view` | `"view:<id>"` | View to unsubscribe from. |
```json
{"v":1,"id":"unsub-001","type":"view.unsubscribe","payload":{"view":"view:buffer"}}
```
---
## Core to UI messages
### reply
**Purpose:** The result of a request. `ok` is true on success; the `result` field carries the return value (which may be `null`). On error, use `error` instead.
**Payload fields:**
| `ok` | boolean | Success flag. |
| `result`| object \| null | Result data. |
```json
{"v":1,"seq":1,"type":"reply","id":"h-001","payload":{"ok":true,"result":{"version":1}}}
```
```json
{"v":1,"seq":1,"type":"reply","id":"sub-001","payload":{"ok":true,"result":null}}
```
```json
{"v":1,"seq":2,"type":"reply","id":"cmd-001","payload":{"ok":true,"result":{"buffer_id":"buf-1"}}}
```
### error
**Purpose:** An error reply to a request. Always echoes the request `id`.
**Payload fields:**
| `code` | string | Machine-readable error code (see §6 error catalog). |
| `message` | string | Human-readable error message. |
```json
{"v":1,"seq":3,"type":"error","id":"cmd-002","code":"unknown_command","payload":{"message":"Unknown command: savv"}}
```
```json
{"v":1,"seq":3,"type":"error","id":"sub-002","code":"unknown_view","payload":{"message":"unknown view: view:nonexistent"}}
```
### event
**Purpose:** A state-change event published on the event bus (architecture.md §10). The `name` is drawn from the §10 event catalog. Unsolicited — not tied to a specific request.
**Payload fields:**
| `name` | string | Event name (see §10 catalog). |
| `data` | object | Event payload. |
```json
{"v":1,"seq":4,"type":"event","payload":{"name":"BufferChanged","data":{"buffer_id":"buf-1","row":0,"col":1}}}
```
```json
{"v":1,"seq":5,"type":"event","payload":{"name":"BufferSaved","data":{"buffer_id":"buf-1","file_path":"/tmp/example.txt"}}}
```
```json
{"v":1,"seq":6,"type":"event","payload":{"name":"CursorMoved","data":{"buffer_id":"buf-1","row":0,"col":5}}}
```
```json
{"v":1,"seq":7,"type":"event","payload":{"name":"FileOpened","data":{"buffer_id":"buf-2","file_path":"README.md"}}}
```
### state
**Purpose:** Full state snapshot for a subscribed view. Sent after each `view.subscribe` reply and after each event that changes the view's state. This is a *projection* of core state — the UI is authoritative only over its own transient rendering.
**Buffer view payload** (the default editor buffer view):
| `view` | `"view:<id>"` | View identifier. |
| `lines` | array[string] | Buffer content, one string per line. |
| `cursor` | object | `{ "row": int, "col": int }` — 0-indexed, matching `BufferActor`'s `GetCursorPosition` reply. |
| `file_path`| string \| null | Current file association, or null for unnamed buffers. |
| `mode` | string | Editor mode (e.g. `"insert"`, `"normal"`). |
```json
{"v":1,"seq":8,"type":"state","payload":{"view":"view:buffer","lines":["hello world","second line"],"cursor":{"row":0,"col":11},"file_path":"README.md","mode":"normal"}}
```
### notification
**Purpose:** An unsolicited human-facing message (info/warning/error). Does not require a request.
**Payload fields:**
| `level` | `"info"` \| `"warning"` \| `"error"` | Severity. |
| `message`| string | Human-readable text. |
```json
{"v":1,"seq":9,"type":"notification","payload":{"level":"info","message":"File saved successfully"}}
```
```json
{"v":1,"seq":10,"type":"notification","payload":{"level":"warning","message":"Buffer has unsaved changes"}}
```
### layout
**Purpose:** Describes the arrangement of views in the workspace (architecture.md §33). Sent at session start and whenever the layout changes.
**Payload:** a layout tree object:
| `root` | string | Root container id (e.g. `"workspace"`). |
| `children`| array[string] | Ordered child region ids (e.g. `["sidebar","main","bottom"]`). |
```json
{"v":1,"seq":11,"type":"layout","payload":{"root":"workspace","children":["sidebar","main","bottom"]}}
```
```json
{"v":1,"seq":12,"type":"layout","payload":{"root":"workspace","children":["main"]}}
```
---
## Error model and versioning policy
### Error reply shape
```json
{"v":1,"seq":3,"type":"error","id":"cmd-002","code":"unknown_command","payload":{"message":"Unknown command: savv"}}
```
An error reply echoes the request `id` (if applicable) and carries a `code` (machine-readable) and a `message` (human-readable) inside the payload.
### Error code catalog
| `invalid_message` | The JSON could not be parsed, or did not conform to the envelope shape (missing `v`, `type`, or `payload`). |
| `unknown_type` | The `type` field is not a recognized message type. |
| `unsupported_version` | The client's requested protocol version is not supported by the server. |
| `bad_request` | The request was well-formed but invalid (e.g. missing required payload fields). |
| `unknown_view` | A `view.subscribe` / `view.unsubscribe` / `focus` / `view.action` referenced an unknown view id. |
| `unknown_command` | A `command` message named a command that is not registered. |
| `capability_denied` | The command or action was syntactically valid but the client lacks the capability to perform it. |
| `internal` | An unexpected internal error occurred. |
### Versioning policy
- The protocol version is an integer in the `v` envelope field.
- **Additive-only evolution**: new message types, new payload fields, and new error codes may be added without incrementing `v`. Existing types are never renumbered or repurposed.
- **Unknown event types are ignored** by clients — a client receiving an event `name` it does not recognize should skip it (forward-compatible).
- **Unknown request `type` values** produce an `unknown_type` error reply carrying the echoed `id`.
- **Unknown error codes** are treated as `internal` by clients (clients should not hard-fail on an unrecognized code).
- **Major version negotiation**: client `hello` declares its version; if the server cannot support at least a compatible major version, it replies with `unsupported_version` and closes the connection. Minor/patch evolution is fully backward-compatible.
```json
{"v":1,"seq":1,"type":"error","id":"h-001","code":"unsupported_version","payload":{"message":"client version 2 not supported; server supports 1"}}
```
---
## Views and wire types
### View addressing
View identifiers follow the rule `view:<id>` where `<id>` is a lowercase-kebab string. The `view:` prefix distinguishes view targets from buffer targets (`buffer:<id>`).
```text
view:buffer
view:status
view:buffer-list
view:problems
```
### View registry
A view is described by six dimensions (architecture.md §32) — **View ID, State, Commands, Events, Layout, Rendering**. The core does not implement every view; extensions provide views and register them in a client-side view registry. Known default view ids are: `buffer` (the editor content), `status` (status bar), `buffer-list` (open buffers), and `problems` (diagnostics). This list is NOT an exhaustive contract — extensions may contribute additional views.
```json
{"v":1,"seq":2,"type":"reply","id":"sub-001","payload":{"ok":true,"result":null}}
```
### Wire types
- **Content** is an array of strings — one element per line. A buffer with no trailing newline has `lines` of length equal to the line count. An empty buffer has `lines: [""]` (one empty string).
- **Cursor** is `{ "row": int, "col": int }`, **0-indexed**, matching the `(usize, usize)` returned by `BufferActor::GetCursorPosition`. Display conversion (1-indexing for status bar, etc.) is client-side.
- **State** is delivered as a full snapshot per view after each event. No diff/patch protocol exists in this version — the client re-renders from the full line array.
- **File path** is a UTF-8 string or null (untitled buffer).
```json
{"v":1,"seq":8,"type":"state","payload":{"view":"view:buffer","lines":["hello","world"],"cursor":{"row":0,"col":5},"file_path":null,"mode":"insert"}}
```
### Layout model
Layouts form a tree (architecture.md §33). The workspace root has children regions. The default three-region layout is:
```text
Workspace
├── Sidebar
├── Main Area
└── Bottom Panel
```
```json
{"v":1,"seq":11,"type":"layout","payload":{"root":"workspace","children":["sidebar","main","bottom"]}}
```
An extension may contribute additional regions. Users customize the layout programmatically via the layout message stream.
### State ↔ events flow
Per architecture.md §18, the flow is:
```text
state → events → UI state → DOM
DOM interaction → command → core
```
The core pushes `state` (full snapshot) and `event` (change notification) messages. The UI applies both and re-renders. DOM interaction (keystrokes, clicks) generates `command`, `input`, or `view.action` messages back to the core.