Skip to main content
Glama
README.md
# stateui-mcp

A standalone MCP server for building StateUI apps. An agent creates and edits an app with tools, a person watches the same app live in a browser, and a headless Chromium (Playwright) renders it so the agent can take screenshots, click and type in it, and read the events it raises.

The server serves no HTTP. It speaks MCP on stdio, and its tools write each app's live state to a [statenet](../statenet) (`@punyts/statenet`). The view page that shows the apps is static: the Vite dev server of `view/` serves it locally, a CDN in production, and it reads the state from that statenet (see [Live views](#live-views)).

It is the single-user, local version of the `ui-builder` bounded context of AI Minion: same tools, arguments, results and error codes, with no workspaces, users or approval policy. The server stores the owner's parts, the instances and the uploaded files as JSON files in its data directory (see [Data directory](#data-directory)). `createServices` takes a `storage` (`ServicesStorage`) in place of `dataDir`: `@punyts/stateui-pg` provides Postgres adapters for those ports, which Magnetic uses.

## Install

Node 22 or newer. The `@punyts/*` packages are not on npm; it is developed in the punyts workspace, where each library is an npm workspace and `npm run setup` at the workspace root clones, installs and builds them, so it runs from there.

```sh
npm run mcp:build                 # at the workspace root: this server, the libraries it uses and the runtime bundle
npx playwright install chromium   # once (setup does it), for ui_preview, ui_screenshot and ui_interact
```

Without Chromium everything else works. `ui_preview` still returns the address a person can open (with `rendered: false` and a note), and `ui_screenshot` and `ui_interact` answer `browser-unavailable`.

The runtime bundle comes from `@punyts/stateui-app` (`dist/runtime-bundle/`, built by `npm run build:runtime-bundle` in that package); the view page's Vite plugin serves it (`stateuiView({ runtimeDir })` points at another build). The plugin will not start with a bundle built before a component was added to the library; it names the missing components and asks for a rebuild.

The 3D renderer chunk comes from `@punyts/stateui-3d` (`dist/runtime-chunk/`, an optional dependency). When it is installed and built the view page's plugin serves it beside the runtime and names it to the view, so an app with a `scene3d` loads it on first mount; without it the page names no chunk, and a scene shows its `_fallback` text.

## Run

Three processes: the statenet, the view page's dev server and the MCP server.

```sh
# The statenet (ws://127.0.0.1:4200/sync) and the view page (http://127.0.0.1:5180/, the runtime frame on 5181)
npm run dev

# The MCP server, on stdin and stdout; an MCP client starts it (below)
node dist/cli.js --data-dir ./data
```

`npm run dev` (`scripts/dev.mjs`) runs the statenet (its data in `./statenet-data`, letting in the pages of `http://127.0.0.1:5180` and `http://localhost:5180`) and Vite (`view/vite.config.ts`) in one process, so stopping it stops both. `npm run statenet` and `npm run view` run each alone. `STATENET_PORT` moves the statenet, `STATEUI_VIEW_PORT` the page (and the origin the statenet lets in), `STATEUI_VIEW_RUNTIME_PORT` the runtime frame.

| Option | Environment | Default |
|---|---|---|
| `--data-dir <dir>` | `STATEUI_MCP_DATA_DIR` | `./data` |
| `--statenet <url>` | `STATEUI_MCP_STATENET` | `ws://127.0.0.1:4200/sync` |
| `--view-url <url>` | `STATEUI_MCP_VIEW_URL` | `http://127.0.0.1:5180/`: the view page `ui_preview` names and the headless browser opens |
| `--stdio` | | accepted for older client configurations; stdio is the only transport |
| `--secret-key-file <file>` | `STATEUI_MCP_SECRET_KEY_FILE`, or the key itself in `STATEUI_MCP_SECRET_KEY` | none: an app that keeps `$.server` is refused |
| `--tool-log <file>` | `STATEUI_MCP_TOOL_LOG` | none: no tool calls are logged |
| `--no-showcase` | `STATEUI_MCP_SHOWCASE=off` (or `false`, `no`, `0`) | on: the component showcase is installed on an empty data directory |

`--port`, `--runtime-port`, `--host` and `--runtime-dir` are gone with the web server; passing one says what replaced it.

**Tool-call log.** With `--tool-log <file>` the server appends one JSON line per tool call: `{ at, tool, ok, errorCode?, requestChars, responseChars, target?, errorCount?, warningCount? }`. `requestChars` is the length of the JSON arguments, `responseChars` the length of the result's text (images are not counted), `errorCode` the `error` of a failed result, `errorCount` and `warningCount` the lengths of its `errors` and `warnings`, and `target` the call's `app` (with `/` and `screen` when it names one), cut to 80 characters. Once per session, when the client has initialized, it also writes `{ at, instructionsChars }`, the length of the served instructions (not their text), so a measurement counts the instructions once per build with the tokens read. Nothing else is written: no arguments, no response bodies. A failed write is reported once on stderr and never fails the call. It is for measuring how agents use the tools: `node scripts/summarizeToolLog.mjs <calls.jsonl>...` prints per build the tokens read (instructions plus catalog plus guide), the instructions tokens, the catalog tokens (the catalog tools and `ui_guide`; characters divided by four), the guide tokens apart, the failed writes and the first-write validation errors, and their median and range over several builds (`test/measurement/requests.md` has the requests and the scripts that run them).

`npm start` runs `node dist/cli.js`; `stateui-mcp --help` lists the options. `stateui-mcp convert` converts the old apps of a data directory into owner parts once (see [Converting the old apps](#converting-the-old-apps)). Every log line goes to stderr, because stdout is the protocol. `Ctrl+C`, `SIGTERM`, or the client closing stdin stops the server, closes its statenet connections and closes the headless browser. The server starts without the statenet and keeps trying to reach it: the tools work meanwhile, and the views catch up once it is there.

## Component showcase

The server ships an app that shows every component of the library, `component-showcase`. Every screen places the same two composed components, `showcaseHeader` (the title and the theme switches) and `showcaseMenu` (a side menu that folds behind a button on a phone); the menu has a home screen, with the number of components per category and a chart of them, and one screen per catalog category (layout, navigation, forms, data, feedback, overlays, content, conversation, graphics). Each component is a card with its name, its catalog summary and a live example with realistic data: tables, lists, boards, calendars and charts read small sample datasets, the overlays open from buttons, the drawings use every 2D shape and the 3D scenes every 3D node, with a model from a GLB file. The header switches between the four theme presets and between light and dark. A logic module, `showcase-tasks`, unassigns a task moved back to To do on the board.

**See it.** When the server starts on a data directory that holds no parts (a new or empty one), it installs the showcase there and logs one line, `Installed the component showcase on the new data directory`. Open `http://127.0.0.1:5180/` and pick `component-showcase`, or ask the agent to `ui_preview` it. The showcase is an ordinary app of parts (an app, four themes, models and datasets, a logic module and an uploaded file), so `ui_get` shows how each example is built and its nodes can be copied into another app. A data directory that already holds parts is never touched, so the showcase is installed once, and an app you change or delete stays that way.

**Turn it off.** Start the server with `--no-showcase`, or set `STATEUI_MCP_SHOWCASE=off`. `startServer` installs it only when its `showcase` option is true, which the CLI sets unless it is turned off.

**Rebuild it.** The parts in `showcase/parts/` are generated and committed: `npm run showcase:build` (`scripts/buildShowcase.mjs`) builds them from the examples in `showcase/examples/` (one file per category, plus `datasets.json`), the catalog of `@punyts/stateui-components` and the files in `showcase/files/`, with fixed ids and dates, so a rebuild with nothing changed writes the same bytes. Run it after adding a component to the library or changing an example; `test/showcase.test.ts` fails when the committed parts are not up to date, when a catalog component has no card (the exclusion list, `EXCLUDED` in the script, is empty) or when the app does not validate, and `test/showcase.integration.test.ts` opens every screen in the headless browser.

## Register it in an MCP client

The client starts the server on stdio; start `npm run dev` first so the views have a statenet and a page.

Claude Code:

```sh
claude mcp add stateui -- node /path/to/stateui-mcp/dist/cli.js --data-dir /path/to/data
```

A `.mcp.json` (the workspace's own uses relative paths, since Claude Code starts it in the workspace folder):

```json
{
    "mcpServers": {
        "stateui": {
            "command": "node",
            "args": ["/path/to/stateui-mcp/dist/cli.js", "--data-dir", "/path/to/data"]
        }
    }
}
```

The server instructions are short (K1.2 of the guide-tool epic): they hold what every build needs and point to the rest. They are built from the guide's topic table (`GUIDE_TOPICS` in `src/infrastructure/mcp/guide.ts`, the one source of the guidance; `ui_guide` answers one topic of it) by `buildServerInstructions`: the opening line; a paragraph on `ui_guide` (`GUIDE_INTRO`: what it is, that its description lists the topics, and to read a topic before the step it names); the always-on topics in full, in table order; then one line per other topic, as a block at the end: "Before <when>, read ui_guide topic <name>." (`pointerLine`). With the library catalog and its four presets they are 5,157 characters, a third of the 15,669 they were with every topic in full; `test/toolSet.test.ts` fails if they grow past half of that. The always-on topics are the eight build steps (`searchWorkflowSection`, the topics `start` and `sections`): plan (`ui_list`; a large app, more than three screens or one that writes to an owner dataset other apps use, waits for the user's OK on the plan), theme (`ui_theme_create`, `ui_theme_write`, `ui_tokens_list`), data (`ui_model_write`, `ui_data_write`), app (`ui_patterns_search`, `ui_app_create`), screens (`ui_patterns_search`, `ui_screen_create`), sections (`ui_components_search`, `ui_component_get`, `ui_nodes_write`), logic (`ui_logic_write`) and check (`ui_validate`, `ui_preview`, `ui_screenshot` full page and at 375 px, `ui_interact`), the order being guidance and an edit starting at the step it needs, with the library's theme presets (`PatternCatalog.presets()`; the line is left out while there are none) and a category index generated from the catalog (each category with its count and three typical members); and the rules that cost a failed call (the topic `keys`: icon names from `ui_icons_list`, token and overlay names from `ui_tokens_list` and `ui_component_get`, no integer-like record keys, no set through a missing parent, `move` over remove and rewrite, never write a `resolved` value back). The other topics are read with `ui_guide`: `parts` (parts the owner keeps by name, build time and run time tools), `paths` (`$.app`, `$.screens.<name>`, `$.route`, rendered paths), `revisions` (a revision per part with its warnings), `modules` (modules and params), `logic`, `live-view` (the live view, the instance state and how to read events), `files`, `safety` (ask before `ui_delete` and `ui_rename`), and the graphics topics, pointer lines too since K1.2: `drawing` (`graphicsSection`): the shape vocabulary, that shapes sit in a drawing, that a shape value is a literal, a token or a link, that a colour from a record comes from the record (`"<-fill": "$row.fill"`), that `draggable` needs `interactive: true` and a drag writes once on release, and that shapes are reached with `ui_tree` `rendered: true` and `ui_interact`; `paint-field` (`paintFieldSection`, two lines): `paintField` is a form field whose value is the reference of the PNG it saves, a form waits for the save, and painting needs a pointer, so a form that must work without one adds a `textField` for a typed signature; and `scene3d`, `scene3d-models` and `scene3d-behavior` (`scene3dSection` joins them, G3.11 of graphics epic 3, releases 3A and 3B; a header and one bullet per subject, 11 lines): `scene3d` and its nodes (`camera`, `light`, `mesh`, `model`, `label3d`, `group3d`, `repeat3d`); that a scene needs `_title` and `_fallback`, and the 16-scene warning (`ui_validate`); the node values (`[x, y, z]`, a mesh's `geometry` and `material`, colours as literals or tokens); the default camera, the `environment` presets and `controls` (`orbit`, `pan`), which write the active camera's `position` and `target` once on release; that `model.src` is the file reference of an uploaded GLB of at most 10 MiB and which models are refused (`SUI-RUN-3D`, `SUI-RUN-FILE`); that `material.map` is the file reference of an uploaded png, jpeg, gif or webp image tinted by the colour (`SUI-STATE-INVALID` for another type); that `repeat3d` draws its `mesh` row once per record as one instanced mesh, each record with its own position, rotation, scale, visibility and `material.color`, the rest shared (`SUI-RUN-DRAW` when records differ there), at most 20,000 records (`SUI-RUN-CAP`); that `interactive: true` with a `_label` raises `press` and `hover` and gives the node a path for `ui_tree` and `ui_interact`; that `label3d` draws plain `_text` in the page font facing the camera (`fontSize` 0.3 scene units by default, the theme text colour); that `transition` eases a node's position, rotation, scale, material colour and opacity, a light's intensity and a camera's position and target, `animate` (`spin`, `bob`, `pulse`) and a model's clip (`animation`, `playing`) play without writing state, and reduced motion turns them off; and that `ui_screenshot` waits for the scene, its models, textures and transitions. A client that does not show the server instructions gets the same text from `ui_guide` with the topic `start`. The descriptions of `ui_list`, `ui_theme_create`, `ui_app_create` and `ui_components_search` end with the start of the working loop and the rules that cost a failed call (`START_HERE`, which names `ui_guide` once), and each tool description starts with `Build time:` or `Run time:` (`ui_guide`: `Guide:`).

## Tools

Thirty-eight tools: the guide, then three groups: build time, the owner's data and run time. Build time tools change definitions (parts) and never touch an instance; run time tools act on the default persona's instance of an app part and never change a definition. `ui_guide` is neither: its description starts with `Guide:`.

**The guide's topics.** `ui_guide` answers one topic by name, and the server instructions name the topic to read before each step ("Before <when>, read ui_guide topic <name>."); the topics marked always on are in the instructions in full. `start` (always on): the whole server instructions, for a client that does not show them; `sections` (always on): the later build steps, the theme presets and the component categories; `parts`: before planning the parts of an app; `paths`: before writing a node, screen or route path, or looking at a running app with `ui_tree`; `revisions`: before changing a part that exists; `keys` (always on): before naming an icon or token, giving a record key or setting a value under a path; `modules`: a logic module or the params of a screen; `logic`: a machine or rule; `tables`: a lookup table; `effects`: a compute unit, an effect, a request token or paged records; `live-view`: before previewing, testing or watching a running app; `files`: before reading a file a user uploaded; `drawing`: a drawing and its shapes; `paint-field`: a paintField; `scene3d`: a scene3d, its node values and its camera; `scene3d-models`: a 3D model file, a texture or a `repeat3d`; `scene3d-behavior`: a pressable 3D node, a `label3d`, 3D motion or the check of a scene; `safety`: before deleting or renaming a part. A client that drops the server instructions still has them: `ui_guide` with `{ topic: 'start' }` answers the same text. A failed call whose code has a topic carries `guide: '<topic>'` in its body, and so does each validation error or warning (see below), so the agent reads the rule the call broke.

| Tool | Arguments | Result |
|---|---|---|
| `ui_guide` | `topic?` | `{ topic, text }`, one topic of how-to guidance; no `topic` answers the index `{ topics: [{ name, when }] }` (`when`: the step the topic is read before). The description lists the topic names: `start`, `sections`, `parts`, `paths`, `revisions`, `keys`, `modules`, `logic`, `tables`, `effects`, `live-view`, `files`, `drawing`, `paint-field`, `scene3d`, `scene3d-models`, `scene3d-behavior`, `safety`. Each text is at most 2,000 characters and is the same for one server build (the `start` and `sections` texts carry the catalog's presets and category index), except `start`, which answers the whole server instructions for a client that does not show them (it is their copy, not a topic of its own; its table text is build steps 1 to 5). Read-only: it reads no storage and changes nothing. An unknown topic is `unknown-topic` with `topics`, the names |
| `ui_components_search` | `need`, `category?`, `tier?`, `limit?` (5, at most 20) | `{ results: [{ name, category, tier, summary, matched, example, source }], weak, categories? }`, library and owner components (`ui_composed_write`) ranked together, best first and never empty; `source` is `library` or `owner`, an owner component without summary, category and purposes is found by the words of its name only, and an owner phrase may repeat a library one (both rank): `weak` when nothing fits well, and a need that matches nothing gets the category index and the nearest category's components; an unknown `category` or `tier` is `invalid-argument` with `allowed` |
| `ui_component_get` | `name` | the compact catalog entry (properties with only the keys that apply, slots, events, commands, tokens, example; a composed component's tree and exposed paths); an unknown name is `unknown-component` with `nearest` |
| `ui_icons_list` | `query?`, `category?`, `filled?`, `limit?`, `app?` | `{ icons: [{ name, category, tags, hasFilled, source }], total, more }`; `source` is `set`. Given `app`, the app's own icons (`ui_icons_write`) that match come first with `source` and `category` `app`, and a set icon of the same name is left out, since the app's wins; an unknown app is `not-found` with `nearest` |
| `ui_tokens_list` | `group?`, `query?`, `includeOverlays?` | `{ count, tokens, overlays? }`; `unknown-group` lists the groups |
| `ui_patterns_search` | `need`, `kind?` (`shell` or `screen`), `limit?` (5, at most 20) | `{ results: [{ name, kind, summary, matched, slots, params, components, source }], weak }`, the library's patterns and the owner's (`ui_pattern_write`) ranked together, best first and never empty; `source` is `library` or `owner`, and an owner pattern may share a library pattern's purposes (both rank): `weak` when nothing matched or the best match holds none of its purpose phrases; a need that matches nothing gets the patterns of the kind (of both kinds when no kind is given or the kind has none); a missing or blank `need` and an unknown `kind` are `invalid-argument` (with `allowed`) |
| `ui_tree` | `app`, `persona?`, `screen?`, `content?`, `logic?`, `path?`, `depth?`, `paths?`, `rendered?` | `{ app, revision, text, lineCount, cutLines, nodeCount?, screens? }`. It shows the default persona's instance (`OutlinePartApp`): the app node with each screen drawn below it under its name, each screen node with its runtime path (`$.screens.home.children.form`); `screen` draws only that one. `content: true` gives the content outline (text, links, marks, record counts from the instance) instead of the structure; `logic: true` adds each machine with its current state in the instance, then the rules, guards and tables, each compute unit and each effect with its status from the instance, a module's units with the module as prefix (`cart:totals`). Default: the structure as a nested list, one line per node with key, component and state path, bullets alternating `-` and `*` by level, slot nodes marked `[slot]`. `rendered: true` lists what the headless page draws instead: rendered rows and cards with their runtime paths (`…board.cols.k_open.body.main.slots.0`), the interactive shapes of drawings (component from `data-shape-kind`, `…rows.<recordKey>` for a `drawRepeat` copy), `(hidden)` nodes with their subtree counted |
| `ui_validate` | `app` | `{ app, revision, valid, errors, warnings, uses, functions }`: the app assembled with every part it uses, each error naming its `part`; `functions` are the functions it names, each entry or `{ path, missing: true }` |
| `ui_state_get` | `app`, `persona?`, `path?`, `full?` | `{ app, revision, source, state, preview }`, or with `path` `{ app, revision, source, path, value, preview }`; `source` is `instance`, the state of the running instance (`unknown-path` names the closest part that exists). `state` is `{ data, app, screens, route }`, and `theme: { active }` once the user picked a theme or overlay. `data:` URIs and strings over 300 characters are shortened unless `full: true` |
| `ui_state_set` | `app`, `persona?`, `path`, `value` or `remove: true`, `logic?`, `expectedRevision?` | `{ app, revision, path }`; the value syncs to every open view, missing parents are created, `remove: true` removes an entry under `$.data`, `logic: false` writes past the guards with no rule firing. A definition path is refused (`definition-path`), a shared dataset too (`shared-dataset`, change it with `ui_data_write`) |
| `ui_state_reset` | `app`, `persona?`, `expectedRevision?` | `{ app, revision }`; the running instance stops, its instance and persona records are removed and its views reconnect to a fresh one; the logic starts again with an empty trace |
| `ui_preview` | `app`, `persona?`, `screen?`, `params?` | `{ app, revision, url, rendered, errors, note? }`; opens the headless page, or reloads it when it is already open, and waits for the revision. `screen` and `params` open that screen first (the instance stays there); an unknown screen is `invalid-argument` with `screens` |
| `ui_command` | `app`, `persona?`, `target`, `command`, `value?` | `{ app, revision, command, previewAttached, message }`; delivered to every open view, the headless page included. `navigate` takes a screen name as `target` and the params as `value` |
| `ui_file_read` | `app`, `persona?`, `fileId` | `{ file, text, truncated, note? }` |
| `ui_screenshot` | `app`, `persona?`, `screen?`, `params?`, `path?`, `width?`, `height?`, `mode?`, `fullPage?` | an MCP image (PNG) and `{ app, revision, target, width, height, mode?, screen?, scenes?, pending? }`; `screen` and `params` as for `ui_preview`. After the viewport is set and the `mode` message sent, the capture waits (up to 10 s) until no drawing or scene in the runtime frame is `data-render="pending"`, then settles and looks once more (a scene that lost its WebGL context while the page settled is `pending` until it has drawn again after the restore); one still pending is named in `pending` with `scenes: "pending"`, and the capture is taken anyway. The headless Chromium is started with no arguments: it draws WebGL2 on SwiftShader as it is (G3.1, G3.10), and a page screenshot captures a scene's canvas without `preserveDrawingBuffer` |
| `ui_interact` | `app`, `persona?`, `actions: [{ action: click|fill|press|hover|select|choose|focus|key|drag, path?, value? }]` | `{ app, revision, results, errors, emits, cursor }`; an error (`action-failed`) when an action failed. `choose` picks a radio option by value or label, `focus` focuses the node or its nearest focusable ancestor, `key` presses a key on whatever has focus (no path), `drag` drags the node onto the node whose path is `value`, or by `value` `+dx,+dy` (page pixels, signed whole numbers) from the middle of its box; a malformed offset is `invalid-argument` showing that form. An action whose element was re-rendered meanwhile is tried again. On the path of a shape: `click` is a real pointer click on an SVG shape (hit testing runs) and an element-level click on the hidden proxy button of a canvas shape, `hover` moves the mouse to the middle of its box, `focus` focuses it, `press` and `key` (with the path) focus it and press the key, `drag` drags it (on canvas the press lands on the canvas beneath the proxy); a shape that is not draggable (`interactive: true` and `draggable`) is refused before the mouse goes down, so nothing moves; `fill`, `select` and `choose` are refused naming the actions a shape takes. It waits for pending drawings before the actions and after them (`scenes`, `pending` as for `ui_screenshot`) |
| `ui_events_read` | `app`, `persona?`, `since?` (or `cursor?`) | `{ app, events: [{ cursor, name, payload, at, view }], cursor }`; logic adds `logic.failed`, `logic.call` (`{ id, name, payload }`, view `logic`) and `logic.effect` (`{ id, name, token, request }`, view `logic`) |
| `ui_call_answer` | `app`, `persona?`, `id`, `status` (`accepted` or `rejected`), `value?`, `reason?` | `{ app, id, answered: true }`; the machine that made the `logic.call` gets the answer as its result; `not-waiting` when no call with that id waits |
| `ui_effect_answer` | `app`, `persona?`, `id`, `records?` (a list), `first?`, `total?`, `value?`, or `error?` | `{ app, id, answered: true }`; the effect that raised the `logic.effect` gets the answer and commits it like a function's (records into its data map by key, the window, the status `ready`), or the status `error` with the reason; only the latest request of an effect waits, so an older id is `not-waiting` |
| `ui_logic_trace` | `app`, `persona?`, `limit?`, `clear?` | `{ app, runs: [{ at, cause, changes, events: [{ depth, kind, name, outcome, path?, from?, to?, row?, writes?, reason? }] }] }`: the last runs of the logic (at most 25 kept), one event per unit whose trigger matched, and `effects: [{ name, token?, running, cached }]`; `no-logic` when the logic does not run on the server |

The tools of the owner's parts (`kind` is one of `apps`, `themes`, `logic`, `models`, `data`, `components`, `patterns`, `screens`, and `screens` takes `app`):

| Tool | Arguments | Result |
|---|---|---|
| `ui_list` | `kind`, `query?`, `app?` | `{ kind, count, items: [{ name, revision, updatedAt, title?, uses? }] }`, by name; screens: `{ kind, app, revision, count, items: [{ name, title?, start? }] }`. `query` keeps the items with every word in the name or title |
| `ui_get` | `kind`, `name`, `app?`, `path?`, `depth?`, `resolved?` | `{ kind, name, id, revision, path, value, resolved, note? }`; a screen has its app's id and revision; `resolved` (apps only) is the assembled app; `not-found` with `nearest`, `missing-path` |
| `ui_delete` | `kind`, `name`, `app?`, `expectedRevision` | `{ kind, name, revision }`; `in-use` with `users` (a used part); a screen's answer adds `start`, the app's start after it (`null` when no screen is left: any screen may be deleted, the start passing to the next), `conflict`, `not-found`. Deleting an app also stops and deletes its instance and persona records, removes its side folder (preview errors and uploaded files) and closes its views |
| `ui_rename` | `kind`, `name`, `to`, `app?`, `expectedRevision` | `{ kind, name, revision, rewritten: [{ kind, name, revision }] }` (`RenamePart`); `duplicate-name`, `invalid-name`, `conflict`, `not-found` |
| `ui_app_create` | `name`, `icons?` (the app's own icons, as `ui_icons_write` writes them, so `home` may name them from the start), `app?` (the app node, `{ "component": "app" }` with its `layout`, `toasts` and `on`; the title becomes its `_title`), `home?` (the root of the first screen: a node tree, or `{ pattern, params? }`, a library or owner screen pattern; a bare `panel` when left out), `title?`, `themes?`, `data?`, `logic?` (the three parts of `uses`) | `{ name, id, revision, start: "home", slots, warnings }` (`CreatePartApp`): the app starts with one screen, `home`. A pattern is copied once with `applyPattern` (each param left out takes its default) as ordinary nodes, and `slots` lists its places to fill as `{ name, path, description }` with node paths under `$.app` (empty for a node tree). `not-found` with `missing: [{ kind, name, nearest }]`, `invalid-app` with `errors` (each naming its `part`; a link under `$.data` to nothing adds a hint on what to bind), `invalid-argument` for an app node that is not an `app`, an unknown pattern (with `nearest`), or param values (`argument: "home.params"`, `params` naming each) |
| `ui_app_configure` | `name`, `expectedRevision`, `title?`, `uses?`, `start?`, `ephemeral?`, `screens?` | `{ name, revision, warnings }` (`ConfigureApp`): only those fields change; a new `uses` replaces the old one and is checked whole; `screens` names every screen once, `{ name, title? }`, in the new order, and a title retitles it (`""` removes it). `not-found`, `invalid-app`, `conflict` |
| `ui_screen_create` | `app`, `name`, `expectedRevision` (the app's), `title?`, `params?` (the screen's typed params), `root` or `pattern` (a library screen pattern) with `patternParams?` | `{ app, name, revision, slots, warnings }` (`CreateScreen`), with the app's new revision; `slots` as for `ui_app_create`, with node paths under `$.screens.<name>`. `duplicate-name`, `conflict`, `not-found`, `invalid-app`, `invalid-argument` for an unknown pattern (with `nearest`) or param values (`argument: "patternParams"`) |
| `ui_nodes_write` | `app`, `screen` (a screen name, or `"app"` for the app node and its toasts), `expectedRevision` (the app's), `operations` (`add`, `set`, `merge`, `remove`, `move` on paths that start with `root`, or `$.screens.<screen>...` / `$.app...`) | `{ app, screen, revision, warnings, added: [{ index, path }] }` (`WriteNodes`): the operations apply in order to the one tree, then the app is checked whole. `add` takes `key?`, `before?`, `after?`. `invalid-operation`, `invalid-app`, `conflict`, `not-found` |
| `ui_locale_write` | `app`, `screen` (or `"shell"`), `language`, `expectedRevision`, `operations` (`set`, `remove` on content paths) | `{ app, screen, language, revision, warnings }` (`WriteLocale`): the overlay of that language for that tree; each content path still untranslated is a `SUI-LOCALE-MISSING` warning. An emptied overlay is removed. `invalid-argument`, `invalid-operation`, `invalid-app`, `conflict`, `not-found` |
| `ui_icons_write` | `app`, `expectedRevision` (the app's), `operations` (`set` of an icon by `name` with `outline` and optionally `filled`, each a list of paths: the `d` of an SVG path in a 24×24 view box, or `{ d, fill?, stroke?, opacity? }`; `remove` by `name`) | `{ app, revision, icons, warnings }` (`WriteIcons`): the app's own icons, for glyphs the icon set does not have. A node names one as it names any icon, and it wins over a set icon of the same name. Path data only (no markup, `url(` or other attributes, checked by `appIconProblems` in `stateui-app`), so a circle is written as a path. The view of the app gets them in its document, so the attach message looks up only the other names in the icon set. `invalid-app` with each problem at its path, `invalid-operation` for removing an icon the app does not have, `conflict`, `not-found` |
| `ui_theme_create` | `name`, and `from` (a theme to copy) or `preset` (an enum of the library's presets, each described with its summary; a free string saying there are none while the catalog has none) | `{ theme, revision, warnings, contrast, reaches }` (`CreateTheme`): a copy with its own id at revision 1. `invalid-argument` for an unknown preset, naming the presets there are (the library ships `clean`, `moody`, `professional` and `playful`), `not-found`, `duplicate-name`, `invalid-name` |
| `ui_theme_write` | `theme`, `expectedRevision` (leave it out to create the theme from no tokens), `operations` (`set` and `remove` of a token, at the base or in `overlay`; `add-overlay` with `kind`; `remove-overlay`) | `{ theme, revision, created, warnings, contrast, reaches }` (`WriteTheme`, through `WritePart`): `contrast` lists `{ mode, text, surface, ratio, passesAA }` for each text pair in each mode (`ratio: "unresolved"` when a side is not an opaque colour); `reaches` the components whose own tokens refer to each written token; `warnings` the apps the write breaks. `invalid-theme`, `invalid-operation`, `conflict` (also for a create of a theme that exists), `not-found`, `invalid-name` |
| `ui_model_write` | `model`, `expectedRevision` (leave it out to create the model), `operations` (`set` of a field with `type`, `default`, `required`, `validators`, replacing its whole declaration; `remove` of a field) | `{ model, revision, created, warnings, datasetWarnings, readers }` (`WriteModel`, through `WritePart`): `datasetWarnings` lists the datasets of the model whose records no longer fit (`{ dataset, keys, invalidCount }`), `readers` the apps and logic modules whose `$.data.<binding>.<record>.<field>` paths read a removed field (`{ kind, name, paths }`), `warnings` the apps the write breaks. An unknown type or validator is `invalid-argument` with `allowed`; a default that fails its type or its own validators is `invalid-model`. `invalid-operation`, `conflict`, `not-found`, `duplicate-name`, `invalid-name` |
| `ui_data_write` | `dataset`, `model` (only to create the dataset), optional `expectedRevision`, `operations` (`add` with a record `value`; `set`, `merge`, `remove` and `move` on a `path` below the records, such as `p1` or `p1.price`) | `{ dataset, revision, created, added }` (`WriteData`): `added` holds the generated key of each `add` (`r` and an id, never integer-like). Every touched record is checked against the model; a record that does not fit refuses the whole write as `invalid-records`, each error with `record` and `field`. Without `expectedRevision` the write applies to the newest records. Open apps bound to the dataset show the change at once. `conflict`, `not-found` (dataset or model, with `nearest`), `invalid-argument` for a `model` other than the dataset's, `invalid-name` |
| `ui_data_query` | `dataset`, optional `filter` (an expression over `$record` and `$key`), `sort` (`"price"`, `"-price"` or `{ by, direction }`) and `window` (`{ first, count }`, count 20 by default, at most 100) | `{ dataset, revision, records: [{ key, record }], first, total }` (`QueryData`); `total` counts the matching records before the window. A filter that does not evaluate is `invalid-argument` |
| `ui_logic_write` | `app` or `module` (exactly one), `expectedRevision` (required for an app; leave it out to create a module), `operations` (`set` of a unit whole, `remove`; `unit` is `machines.<name>`, `rules.<name>`, `tables.<name>`, `computes.<name>` or `effects.<name>`), and for a module `needs` and `params` (each replaced whole) | `{ app \| module, revision, created, units, warnings }` (`WriteLogic`): `units` gives each unit the write left set with its `position` in the run order (`logicRunOrder` of the app assembled with its modules, or of the module) and the paths it `reads` and `writes`, and `runs` (`server`, the default, or `browser`: where it runs in a Full-mode app); a guard has no position. An app is checked as a whole (`invalid-app`), a module by the module rules through `WritePart` (`invalid-module`, `SUI-MODULE-NODE`, `SUI-MODULE-NEEDS`); `warnings` are the app's, or for a module the apps it breaks. `invalid-operation`, `conflict`, `not-found`, `duplicate-name`, `missing-parts` |
| `ui_composed_write` | `name`, `expectedRevision` (leave it out to create), `tree` (required to create), `exposes` (`[{ path, description }]`), and for the component search `summary` (one line, at most 120 characters), `category` (one of `COMPONENT_CATEGORIES`) and `purposes` (3 to 8 one-line phrases of at most 60 characters, `checkPurposes`) | `{ name, revision, created, searchable, note?, appWarnings, moreApps? }` (`WriteComposed`): the search fields are stored beside the tree and never reach the assembled tree; a write that leaves one out keeps it, `""` or `[]` removes it. `searchable` is true with all three (otherwise `note` says it is found by name only). The part goes through `WritePart` (`invalid-component`, such as `SUI-NODE-CYCLE` for a component that contains itself), and `appWarnings` names the apps the write breaks. A library component name is `invalid-name`. `invalid-argument` names the search field (with `allowed` for `category`), `duplicate-name`, `not-found`, `conflict` |
| `ui_pattern_write` | `name`, `expectedRevision` (leave it out to create), `kind` (`screen`), `summary` and `purposes` (required to create), `tree` or `from` (`{ app, screen }`, the root of that screen; one of them required to create), `slots`, `params` | `{ name, revision, created }`. Writes an owner pattern in the library's `*.pattern.json` format, checked with `readPattern` and `checkPattern` of `@punyts/stateui-app` (owner components count as composed components): a bad slot or param path or a node that fails its shape is `invalid-pattern` with errors at `patterns/{name}.pattern.json`, and nothing is written. A library pattern name is `invalid-name`. Parts left out of an update are kept. Listed, read, renamed and deleted by the generic tools (kind `patterns`) |

Read-only tools carry `readOnlyHint`; `ui_delete` and `ui_rename` carry `destructiveHint`, so the client asks the user. A failed call has `isError: true` and the body `{ error, message, ...details, guide? }`. `guide` names the `ui_guide` topic that explains the code (`guideFor` over `TOOL_CODE_TOPICS` in `src/infrastructure/mcp/guide.ts`; added by `fail()` in `toolKit.ts`, the message is unchanged): `conflict`, `duplicate-name` and `in-use` point to `revisions`, `missing-parts` to `parts`, `missing-path`, `invalid-path`, `unknown-path`, `not-a-node`, `invalid-target`, `unknown-screen` and `not-rendered` to `paths`, `logic-guard` and `not-waiting` to `logic`, and `no-logic`, `unknown-command` and `browser-unavailable` to `live-view`; other codes have no `guide`. Each entry of `errors` and `warnings` in a validation answer (`ui_validate`, the warnings of a write, the errors of a refused write; for the warnings of a part write, the `errors` of each app it reaches) gains `guide` the same way from its catalog code, by the longest prefix in `VALIDATION_PREFIX_TOPICS`: `SUI-LOGIC` to `logic`, `SUI-MODULE` and `SUI-USES-NEEDS` to `modules`, `SUI-USES` to `parts`, `SUI-ROUTE` and `SUI-NODE-MISSING` to `paths`, `SUI-INSTANCE` to `live-view`, `SUI-DOC-ORDER`, `SUI-STATE-TOKEN`, `SUI-THEME-TOKEN` and `SUI-RUN-ICON` to `keys`, `SUI-STATE-PAINT`, `SUI-STATE-LABEL` and `SUI-RUN-DRAW` to `drawing`, `SUI-DOC-LIMIT-SCENES` to `scene3d`, and `SUI-RUN-3D` and `SUI-RUN-CAP` to `scene3d-models`; other entries are unchanged. The runtime errors of `ui_preview`, `ui_interact` and `ui_state_get` carry no `guide`. Codes: `invalid-argument` (with `argument`), `not-found`, `unknown-tool`, `internal-error`, `browser-unavailable`, `not-rendered`, `action-failed`, and the codes in the table. Arguments are plain JSON; extra arguments are refused, so a call with the `appId` of the removed tools fails.

Differences from `ui-builder`: no `workspace-missing` or `user-missing`, no approval marker on `ui_delete` and `ui_rename` (the client can ask the user; the tools are annotated destructive), and the run time tools act on the default persona's instance, as the local owner's only user.

`path` in `ui_screenshot` and `ui_interact` is the state path of a node, such as `$.app.children.form.children.email` (the leading `$.` is optional). It is mapped to the element the component rendered for that node, through open shadow roots. A hidden or closed node has no element. When no component rendered that path, it is mapped to the element with `data-shape-path` equal to it (`shapeTargets.ts`): the SVG element of a shape, or the proxy button of a canvas shape, so a path that names no shape is an error naming the path.

Drawings (graphics epic 1) use the same tools: shape nodes go in a `drawing` node's `children` with `ui_nodes_write` (`ui_components_search` with `category: "graphics"` finds them), `ui_validate` reports the paint, token and label checks, `ui_screenshot` of the drawing's path waits until it is drawn, `ui_tree` with `rendered: true` lists its interactive shapes, and `ui_interact` presses, hovers, focuses or drags one by its path (`drag` with `value` `+dx,+dy` moves it by page pixels; the offset is read by `dragTargetOf` in `src/infrastructure/preview/dragTarget.ts`, and a shape that is not `interactive` and `draggable` is refused before the mouse goes down). A drag writes once, on release: the shape's `x` and `y` (or the record of a `drawRepeat` copy), so a following `ui_screenshot` or `ui_state_get` shows the new position. A `drawImage` (G1.9b) takes a `data:` picture or the reference of a png, jpeg, gif or webp file uploaded to the app (`POST /apps/<id>/files`); the frame reads the file through the host (`fileRead`, G1.9), and `ui_screenshot` waits until the picture is decoded and drawn. The guide topic `drawing` says what `src` may be. That topic `drawing` (`graphicsSection`, above; a pointer line in the server instructions) says the same to the model. The shape vocabulary, the renderers and the events are documented in the `@punyts/stateui-components` README ("Graphics").

3D scenes (graphics epic 3, releases 3A and 3B) use the same tools: a `scene3d` node holds `camera`, `light`, `mesh`, `model`, `label3d` (a text that faces the camera), `group3d` and `repeat3d` (one `mesh` row drawn once per record as an instanced mesh) nodes in its `children` (`ui_nodes_write`; `ui_components_search` with `category: "graphics"` finds them), `ui_validate` checks them and warns past 16 scenes a page (`SUI-DOC-LIMIT-SCENES`), and `ui_screenshot` of the scene's path waits until its first complete frame, models, textures and transitions included (`scenes: pending` in the result when it times out; a playing `animate` or model clip does not hold it back). A `model`'s `src` is the reference of a GLB uploaded to the app (`POST /apps/<id>/files`, the Security notes say which GLB files are taken), and a `mesh`'s `material.map` the reference of an uploaded png, jpeg, gif or webp picture; the frame reads both through the host as a `drawImage` picture is read. With `controls` a person turns or pans the camera in the live view and the camera node's `position` and `target` are written once on release, so `ui_state_get` shows the view. A 3D node with `interactive: true` has a proxy button, so `ui_tree` with `rendered: true` lists it with its path and `ui_interact` clicks, hovers, focuses and presses keys on it as on a 2D shape (G3.8); a `drag` on it turns the camera of a scene with `controls` and is not a press. The scene and its nodes are documented in the `@punyts/stateui-components` README (`scene3d`), the renderer, the chunk and the headless WebGL note in the `@punyts/stateui-3d` README. The guide topics `scene3d`, `scene3d-models` and `scene3d-behavior` (`scene3dSection`; pointer lines in the server instructions) say the same to the model.

## Live views

The live views of the apps live in a statenet. The server is one of its clients; the view pages are the others. Nothing of the server listens on a port.

**The statenet.** `StatenetViews` (`src/infrastructure/statenet/`) connects to the statenet (`--statenet`) with `StatenetLink`, `@punyts/state-sync`'s sync client over a WebSocket, which reconnects with its backoff:

- **The directory**, the namespace `stateui.apps`: the server keeps `$.apps.<appId>` there (`{ name, namespace, revision, updatedAt }`, one entry per app part, written again on every app change), so the view page lists the apps and finds the namespace of the one it shows. A page asks there for an app with the emit `stateui.open { appId }`; the server answers `ready` when it (re)joins, so a page asks again after a restart.
- **One bridge per open app** (`AppBridge`), in the namespace of its instance, `instances.<persona>.<ownerId>.<appId>`. The instance's authority stays in the server (logic, guards, shared datasets, storage on disk) and is the truth: every change it pushes (logic, `ui_state_set`, a shared dataset's write) is written to the statenet, and on every (re)connect the statenet's state is made equal to the authority's (`diffState`, the smallest writes that do it; `$.server` never leaves the server). A change a page made comes from the statenet and goes to the authority as a client change, so guards, model checks and logic run on it. When the authority adjusts or refuses it, the statenet gets the authority's value back and the pages a `rejected` message, which the view raises as `sync.rejected`; unlike a page that talks to its own server, the change shows for a moment first. A definition change restarts the authority; the bridge connects to the new one and writes what changed. A deleted app gets `deleted`, and its bridge stops.
- **The view relay.** Everything that is not state rides the protocol's `emit`, which the statenet relays (an emit from the server goes to every page of the namespace, an emit from a page to the server only, `@punyts/statenet`): the server sends `stateui.server`, a page sends `stateui.view`. Each message is JSON in one or more envelopes `{ v: 1, id, part, parts, text, from?, to? }` (`src/domain/viewRelay.ts`), so a 1 MiB document or a 10 MiB file stays under the protocol's 1,000,000-character message limit. A page sends `hello { kind }` (`browser` or `headless`; the server attaches it to the hub and answers with the app), `report { report }` (ready, rendered, errors, as `takeViewReport` takes them), `event { name, value }` (an `emit` of the app, for `ui_events_read`), `request { id, method, path, … }` (a file upload, read or release, answered with `response { id, status, json?, bytes?, headers? }` as the file routes answer) and `bye`. The server sends `view { message }` (the document, commands, locale, theme, deletion, a refused change), `response` and `ready`. The statenet's `statenet.left { clientId }` detaches a page that closed.

**The view page** (`view/`, `src/browser/statenetView.ts`): `/` lists the apps of the directory, `/?app=<id>` shows the live view of one (`host.ts` with `statenetChannel.ts`), and `?statenet=ws://…` names the statenet (else `VITE_STATENET_URL` from the build, else `ws://<page host>:4200/sync`). `ui_preview` answers `<view url>?app=<id>&statenet=<url>`, the page the headless browser opens too (`?kind=headless` or its user agent marks it). The Vite plugin (`@punyts/stateui-mcp/vite`, `stateuiView()`) serves the runtime frame on a second port, so the sandboxed frame (`allow-scripts allow-same-origin`) has an origin of its own and cannot reach the page; it serves the runtime page with the runtime policy (no network, framed by the page's origin only), the bundle and the 3D chunk, and writes `data-runtime-url` and `data-chunk-3d` on the page's body.

**Production (a CDN).** `npm run view:build` writes the page, `page.css` and `runtime/` (the runtime page, bundle and chunk) to `dist/view/`; no deployment is made. Set at build time: `STATEUI_VIEW_BASE`, the base URL or path the files are served from (Vite's `base`, such as `https://cdn.example.com/stateui/`); `STATEUI_VIEW_RUNTIME_URL`, where the pages load the runtime frame from (`{host}` is the page's host name), on an origin other than the pages', so serve `runtime/` from a second origin with the runtime policy as its `Content-Security-Policy` (`runtimeCsp` in `src/infrastructure/http/security.ts`); without it the frame loads `./runtime/runtime.html` from the pages' own origin; and `VITE_STATENET_URL`, the statenet the pages connect to. Run the server with `--view-url` set to the page's URL, and the statenet with `--allow-origin` set to the page's origin. The statenet listens on loopback only and has no authentication, so a statenet reached from other machines needs a proxy that adds both in front of it.

**How the view works.** The page is a shell with one module. It puts the runtime page into a sandboxed iframe served from the runtime origin, speaks the versioned message protocol of `@punyts/stateui-app/protocol` with a per-load nonce, and checks every message by source, origin and nonce. The app runs in Full mode of `@punyts/state-sync`: the page's sync client syncs with the app's namespace, and the view messages bring the document (on hello and after every part write, written into the running app as path writes where it can, or as a new load), commands and theme or locale switches. Every change a user makes to `$.data` or to the articulation of `$.app` (no `_` content, no `component`, `on`, `layout`, `placement` or `theme`) is synced, and every change the authority applies (another view's, a `ui_state_set`) reaches every view. The sync client keeps the confirmed state, the changes not yet acknowledged and the document in `localStorage`, so the view opens and takes changes while the statenet is away and sends them in order when it is back. `body[data-sync]` and `$.runtime.sync` show the status. Query parameters `?mode=dark` and `?locale=fr` apply a theme overlay or a language to a view. **Files.** The frame has no network, so files pass through the page: a `file` message (a `fileField` upload) goes to the server as a request, a `fileRead` (a component reading a stored file, such as a `paintField` background image) is read through the server (`src/browser/fileRead.ts`) and answered with `fileData`, the bytes moved in the transfer list, and a `fileRelease` (a component giving a stored file back) is answered with `fileReleased` (`src/browser/fileRelease.ts`). An id that is not a UUID is `not_found` (a release `ok: true`) without a request; a 404 is `not_found`, 401 or 403 `unauthorized`, any other failure `internal`, a request that gets no answer `offline`, and a body over 10 MiB is `too_large`. A release is `ok: true` for `204`, `404` and `409` (a file the app or its live state still references stays, and the 24-hour sweep removes it once nothing does), and it waits until the sync client has no change waiting for its ack (at most 5 s), so the write that let go of the file reaches the server first.

### The embedded endpoint

A server that serves its own view pages, with sign-in and many owners, embeds `startHttpServer` (`src/infrastructure/http/HttpServer.ts`) instead: `@punyts/magnetic` does, since a statenet has no authentication to hand to signed-in browsers. Its pages run the same view with the direct channel (`src/browser/viewChannel.ts`, `/assets/host.js`):

| Route | What |
|---|---|
| `GET /` | the apps (app parts), with a link to each |
| `GET /apps/:appId` | the live view of an app part, assembled and with the default persona's instance |
| `GET /apps/:appId/sync?view=<uuid>` | the WebSocket of a view: the state-sync protocol and `{ type: 'view', message }` frames (document, commands, locale, theme, deletion); same origin only |
| `POST /apps/:appId/report` | what a view tells the server: ready, rendered revision and runtime errors |
| `POST /apps/:appId/files` | an upload from a `fileField`: `multipart/form-data` with one field `file`; `201 { id, name, size, type }`, `409 quota`, `413 too_large`, `415 unsupported_type` |
| `GET /apps/:appId/files/:fileId` | the bytes, as an attachment, `nosniff`, `Content-Security-Policy: sandbox; default-src 'none'` |
| `DELETE /apps/:appId/files/:fileId` | releases an upload: `204` removed, `409 referenced` kept because the app part's definition or its instance's live state still holds the id, `404` no such file, `400` an id that is not a UUID; same origin only |
| `GET /assets/host.js`, `/assets/page.css` | the host script and the stylesheet |
| `GET /apps/:appId?surface=page` | the live view with the app in the page itself, not in a frame: the page loads the page bundle before the host script, and the host mounts the app on `[data-app-frame]` |
| `GET /assets/page/<hash>.js` | the page bundle of `@punyts/stateui-app` and the 3D chunk beside it, immutable |

Its runtime port is a second origin that serves only the app frame (`/runtime/<hash>.html`, `/runtime/<hash>.js`, `/runtime/runtime.css` and the 3D chunk `/runtime/<chunk hash>.js`); every other path there answers 404. The host page allows scripts, styles, connections and frames from its own origin only. The page of an app in the page (`?surface=page`, `APP_PAGE_CSP`) has no frames and allows what the runtime page allows, since the app runs on the page's origin: `'unsafe-eval'`, and images and fonts from `data:` and `https:`. Its host gives the page an app host, `stateuiHost.apps`: the live app is attached where an `embeddedApp` asks for it, and a preview of it follows its store. The test harness (`test/helpers.ts`, `httpHarness`) runs the tools with this endpoint, since a view behaves the same over either channel. `stateuiHost.mount(element, { document, icons?, keys?, inPage? })` puts a panel in `element`: a frame from the runtime origin, or with `inPage` in the page surface the page bundle's runtime on an element of the page, whose `embeddedApp` nodes reach `stateuiHost.apps`. A preview from `stateuiHost.apps` is given once the live app is mounted, and each mount of the live app raises `stateui:ready` on `window`, so a page opens its previews again on the new store. `stateuiHost.pages({ open, mounted?, disposed? })` gives the app host the site's own pages: an `embeddedApp` that asks for a name `open(name)` answers (`{ document, icons?, keys?, title? }`) gets that page as a panel in the page filling its frame, `mounted(name, panel, element)` is handed the panel, `disposed(name, panel)` is called with that panel when it is let go, and its emits reach the `embeddedApp` and `stateui:emit` on the element.

**Logic.** A Full app's authority runs the document's `logic` (see `@punyts/stateui-app`): the units without `runs` or with `runs: "server"` (`logicFor`); a unit with `runs: "browser"` runs in the person's page instead, and its writes come to the authority as the person's changes do. A change a view sends runs the logic after it is applied and acknowledged; a guard rule (a rule whose only command is `reject`) answers before, so a refused change is rejected and the view gets `sync.rejected`. `ui_state_set` asks the guards too (a refused value is `logic-guard`) and then runs the logic. A transition's writes reach the views as one `changes` message. The authority keeps `$.app` sparse, so logic reads `$.app` as the document's value with the shape defaults under what the authority holds. `notify.<name>` and `logic.failed` reach the views as app events (the root node's `on`); `emit` and failures are also queued for `ui_events_read`. `ui_tree` with `logic: true` lists the machines with their current state, the rules, the guards and the decision tables with their rows. Timers (`after`, `debounce`) run in the server process and are lost on a restart, where they are armed again. A `call` command runs the procedure of that name given to `startServer` (`procedures`: `(payload, { appId }) => LogicAnswer`); any other call is queued as a `logic.call` event for `ui_events_read`, and the agent answers it with `ui_call_answer`. At most 100 calls wait per app, and waiting calls are dropped on a restart or when the app is removed. Compute units, effects and expressions run the functions named by path in the catalogs given to `startServer` as `functions` (`InstanceCatalog`: a `FunctionCatalog` that may also have `loadFor(id, instance)`, which builds the code for one running app; `catalogFor` binds it). The components' own catalog, `COMPONENT_FUNCTIONS` from `@punyts/stateui-components`, is always installed before them. The validator checks apps against the same entries (`SUI-LOGIC-FUNCTION`, `SUI-LOGIC-FUNCTION-FIT`), `ui_validate` answers with the `functions` the app names (each entry, or `{ path, missing: true }`), and the guide topic `functions` lists them. `copyAppParts` with `functions` (the server's entries, `Services.functions`) answers with `missingFunctions`, the paths the copied app names that this server lacks. So an API key an effect needs stays on the server, and an effect whose `records.into` is a `$.server` map keeps its records there while the views get only the window and the status. An effect with no function is queued as a `logic.effect` event (`AppEffects`, at most 100 per app) and the agent answers it with `ui_effect_answer`; a newer request of the effect aborts the waiting one. `ui_logic_trace` lists each effect's token, whether a call runs and how many answers its cache holds.



**Playwright.** The server keeps one headless Chromium, started on the first call that needs it and closed on shutdown, with one page per app. The page loads the same view page a person opens (`<view url>?app=<id>&statenet=<url>`), so it is a view like any other: it receives the same messages, `ui_command` reaches it and its changes sync like any view's. `ui_screenshot` and `ui_interact` look up the element in the runtime frame and use Playwright's own click, fill, press, hover and select on the native control inside it, so the events are the ones a user raises.

**Policy.** The embedded endpoint's host page allows scripts, styles, connections and frames from its own origin only, no inline script, no inline style, no framing by other pages; the statenet view page is the CDN's (or Vite's) to set. The runtime page has `default-src 'none'`, scripts only from its own origin plus `'unsafe-eval'` (the expression library builds functions for binding expressions), no network, images and fonts as `data:` only, and may be framed by this server's pages only. Uploaded files are never served inline.

## Data directory

The directory holds the owner's parts, one file each, the default persona's instances and, per app part, a side folder with its preview errors and uploaded files. The old single-document store (one folder per app with an `app.json`) is gone: the tools no longer read it, and only `stateui-mcp convert` does.

```text
data/<appId>/                       the side folder of an app part: errors.json, files.json and files/ (below); an old app's folder keeps them after convert
data/<kind>/<id>.json               an owner part; data/names.json indexes them by name (Owner parts, below)
data/rename.pending.json            the journal of a rename stopped halfway, replayed at start
data/personas/default/...           the default persona's instances and persona records
data/.converted/<appId>/            app.json and state.json of a converted app, until convert --purge
```

The side folder of an app part is named by its part id. The old store used the same folder for its `app.json` and `state.json`, which `stateui-mcp convert` reads and moves away:

```text
data/<appId>/app.json      the old store only: id, name, revision, createdAt, updatedAt and the document
data/<appId>/state.json    the old store only: the synced state, its sync revision and change log
data/<appId>/errors.json   the bounded preview error log (the newest 50); a view that renders again drops the errors of its earlier loads and of other views
data/<appId>/files.json    metadata of the uploaded files
data/<appId>/files/<id>    the bytes of one uploaded file
```

Every file is written to a temporary file in the same folder and renamed into place, and the writes of one app run one at a time, so a reader never sees half a file and a write is checked against the revision it read. `children` and keyed data maps are ordered by key: the files are written with `JSON.stringify` and read with `JSON.parse` and nothing re-sorts them (integer-like keys are refused, because JavaScript would move them). Limits: 1 MiB per document, 2000 nodes, 10 MiB per file, 50 files and 100 MiB per app. Uploaded files that nothing references (not in the app part or in the state of its instance, read live from the instance's authority; `$.server` is not included) are removed after 24 hours, when the next upload to the app happens.

**Owner parts.** The owner-tree design moves apps to reusable parts (apps, themes, logic modules, models, datasets, components, patterns). `UiPart` (`src/domain/UiPart.ts`) is one stored part: an immutable UUID `id`, the `kind`, a slug `name` (`isPartName` of `@punyts/stateui-app/core`), the `revision` and the `body` of its kind. `UiPartRepository` (`src/application/ports/`) is the storage contract for every kind: `create`, `findByName`, `findById`, `list`, `write` and `delete` with `expectedRevision`, and `rename`; results are `created`, `written`, `deleted`, `renamed`, `conflict`, `not-found`, `duplicate-name` or `invalid` (a name that is not a slug, a body that is not an object, or a given `id` that is not a UUID or that a part of the kind has). `create` takes an optional `id` so the converter can keep an old app's id. `FilePartRepository` stores them in the same data directory, (`PartFolders` builds every path, from a kind and a UUID only):

```text
data/<kind>/<id>.json      id, kind, name, revision, createdAt, updatedAt and the body; kinds: apps, themes, logic, models, data, components, patterns
data/names.json            { <kind>: { <name>: <id> } }
```

A rename moves no file. The part file is the truth and is written first; `names.json` is an index written after it and rebuilt from the part files at the first call when it is missing or disagrees. Writes to one part run one at a time, and creates, renames and deletes of one kind run one at a time, so two creates of one name cannot both win. `partRepository.contract.test.ts` runs the same cases against `FilePartRepository` and the in-memory fake (`src/testing/InMemoryUiPartRepository.ts`). `UsageIndex` (`src/application/`) knows who uses what: an app's themes, datasets, persona models, logic modules and the components in its nodes, a module's `needs`, a dataset's model and the components in a component's tree. `IndexedUiPartRepository` builds it from the stored parts at the first call and keeps it in step with every change; `deleteRule` refuses to delete a part while anything uses it and names the users; a screen may always be deleted. `WritePart` (`src/application/use-cases/`) checks a part with the reader of its kind and refuses it with its own errors, writes it with `expectedRevision` (or creates it on a first write), then checks every app that reaches it and returns the ones it breaks as warnings (at most 20, with `moreApps`); a model write also names the dataset records that no longer fit. `ValidatePartApp` checks one app assembled with everything it reaches, each error naming its part.

`RenamePart` (`src/application/use-cases/`) renames a part and rewrites every part that names it, all together: theme lists, bindings' `dataset` and `model`, `uses.logic` keys (in their place), `needs` models, datasets' models and the composed names in nodes. It checks the new name as a slug that is not taken, keeps the part's id (so instances and persona data stay where they are) and gives the renamed part and each rewritten one the next revision; it reads again and retries when a part it rewrites moved meanwhile. `UiPartRepository.rename` takes those new bodies as `rewrites`. When it writes more than one part file, `FilePartRepository` first writes `rename.pending.json` (every part file with its new content), then the part files and `names.json`, and removes the journal last; a rename of a part that nothing names writes that part and `names.json` only. A journal that is still there was stopped halfway: `FilePartRepository.recover` (run by `startServer` before anything reads a part, and before the first call reads the names) writes the files that differ from it, removes it and rebuilds `names.json`; running it again changes nothing. Renaming a screen (`kind: "screens"`) is a write of its app with the app's revision: the key in `screens` in its place, `start` and every `navigate` to it.

A dataset part is `{ model, records }`, the records an ordered map. `WriteData` changes them with record operations whose paths are relative to `records` (`p1`, `p1.price`): `add` (a new key, `r` and a new id, so it is never integer-like; the result lists the keys it gave), and the document operations `set`, `merge`, `remove` and `move`. It checks every record the write touches against the dataset's model (`checkRecord`, errors at `$.records.{key}` naming the field) and writes nothing when one is invalid; records it leaves alone are not checked. `expectedRevision` is optional: without it the operations are applied to the newest records, again when another write got in first, so writes to different records do not conflict. Every committed write raises the dataset's revision by one. `QueryData` filters, sorts and windows a dataset's records with `queryRecords` of `@punyts/stateui-app/core`, the evaluator of the logic `query` command, and returns the window with the `total` that matched.

What a person does in an owner app is its instance, kept apart from the definition. `UiInstanceRepository` (`src/application/ports/`) stores the default persona's instance of each app as a diff over the definition (`diffInstance` of `@punyts/stateui-app/core`), and the records of each persona binding (`uses.data.{binding}` with `scope: "persona"`, which has no part). `FileUiInstanceRepository` keeps them by app id, so a rename of the app keeps them:

```text
data/personas/default/apps/<ownerId>/<appId>.json    the diff (app, screens, route, theme, data); no file when nothing differs
data/personas/default/data/<appId>/<binding>.json    { model, records }; a capital in the name is ^ and its small letter
```

The owner id of the local server is `LOCAL_OWNER_ID` (`ownerId` of `createServices` overrides it). A missing file reads as the definition, and a file that cannot be read is ignored with a `problem` the caller reports, never thrown at the person. Nothing there writes a part, and a part write never touches an instance. `WritePersonaData` checks the records against the binding's model as a dataset part's are checked; `ResetInstance` removes the instance and the persona records.

A running instance has its own state-sync authority. `AppAuthorities` is keyed by sync namespace, `instances.<persona>.<ownerId>.<appId>` (`appNamespace`). An instance's state is the assembled view: `$.app` and `$.screens` sparse, `$.route`, and `$.data` by binding, holding a copy of each shared dataset and the persona's records, with the instance laid over it. Its logic is the assembled logic, the app's units plus its bound modules. `InstanceNamespaceStorage` keeps that state as the instance (the diff and the persona records), never the shared copies or `$.server`. It keeps no sync log, so a loaded instance's revision is the clock in milliseconds and a view from before a restart gets a snapshot. `AuthorityInstanceStates` assembles the app on every call and restarts the instance over a changed definition; a change of only the records of a shared dataset is not one (`definitionText`).

Instances that bind one shared dataset see each other's changes through `DatasetHub` (`src/infrastructure/sync/`), which each instance's authority is attached to when it starts:

- Before a change is applied, the records it touches are checked against the dataset's model, synchronously, with the model read once and again when it changes. A client change is refused in the authority's `onChange` handler; a write of the instance's logic or of a tool is refused by the data gate that `AppAuthorities` gives each `AppLogic` (`InstanceDataGate`), and the logic engine asks it as `LogicHost.guard`, so a `save-data` gets the reason as its `rejected` result. The reason is `SUI-MODEL-FIELD`'s message, naming the record key and the field.
- After a change is applied (`onApplied` for a client change, the gate's `applied` for a server write), each record it touched is written to the dataset part whole with `WriteData`, one write-through at a time per dataset. A change that leaves the records as the dataset has them writes nothing, so instances whose rules derive the same value settle. A committed write-through is applied to every other binding of the dataset with one `writeAll` each (`AppAuthorities.receiveInstance`, after which that instance's logic sees the change); a failed one puts the stored records back into the instance and is reported (`Shared data not written`).
- A write of the dataset part from elsewhere (a tool, a rename, a model change) raises its revision past the hub's, and what changed in the records is applied to every binding.
- Persona bindings are never attached. Fan-out writes are server writes, which fire no `onApplied`, so the hub never sees them again. `SetPartState` writes `$.app`, `$.screens.{screen}` and persona `$.data.{binding}` paths, and refuses content, `$.theme` and the other definition roots (`definition-path`), shared datasets (`shared-dataset`, naming `ui_data_write`) and `$.route` (use `navigate`).

The live view of an owner app has the same URL, `/apps/<appId>` with the app part's id. Its page shows the assembled app (`InstanceViews`: the app node, the screens, the themes, the bound data and modules) with the default persona's instance laid over it (the runtime's `load` takes it as `instance`), and its sync client talks to that instance's authority (`data-namespace` on the page). Besides `$.data` and `$.app`, the view syncs each screen's articulation (`$.screens`), the route (`$.route`) and the persona's choice of theme and overlays (`$.theme.active`, never the tokens); a route moved in another view arrives as a `navigate` command, and a theme picked in another view as writes to `$.theme.active` (the theme first). An overlay the server applies to one view (the `mode` of `ui_screenshot`, `?mode=`) stays in that view and is not synced. Every part change that succeeds (`IndexedUiPartRepository.onChange`) reaches the open views of the apps that show the part (`LiveViews.partChanged`): the page writes a change of the app node in place and loads a changed theme, locale, screen or component again in full. A changed definition also restarts the instance's authority, so the views reconnect and get its state. The revision a view of an owner app reports is counted by `InstanceViews`, one more each time the assembled document changes, from 1 at start. `BrowserPreview.open` takes a screen and params (`?screen=<name>&params=<json>` on the view URL) to open the app there instead of where its instance is.

### Converting the old apps

`stateui-mcp convert` turns each app folder that still has an `app.json` into owner parts, once. Stop the server first.

```sh
node dist/cli.js convert --data-dir ./data --dry-run   # print the report, change nothing
node dist/cli.js convert --data-dir ./data             # convert
node dist/cli.js convert --data-dir ./data --purge     # later: delete data/.converted/
```

For each app, `convertDataDir` (`src/config/`) runs `splitDocument` of `@punyts/stateui-app/core` on the document, with the live data of `state.json` in place of the document's (the articulation is dropped), and creates the parts: its themes, a dataset and an inferred model for each key of `data`, its components, then the app, whose part id is the old app id. Names that a stored part or an earlier app of the run has get another one, and the report lists them. The default persona's instance is cleared, then `app.json` and `state.json` move to `data/.converted/<appId>/`; `errors.json`, `files.json` and the uploaded bytes stay in `data/<appId>/`, so the app's files are still listed under the same id. An app the converter cannot split (a rule that switches a hidden tab strip, for one) keeps its files where they are and is listed with the reasons. The plan is made from the stored files alone, so a dry run prints the same report and writes nothing. A second run converts nothing new; when an earlier run created an app's parts and stopped before moving its files, the next run only moves them. The command exits 0 with a report, `Nothing to convert in <dir>.` when there is nothing, and 2 for an unknown option.

**Run it once after installing this version.** The old tools (`ui_app_create` with no app node, and the tools that read an app by `appId`) are gone and the server no longer reads `app.json`, so an app that is not converted is not reachable. The upgrade:

1. Stop the server.
2. `stateui-mcp convert --dry-run` and read the report: the parts each app becomes, the names that changed and the apps that cannot be converted, with the reasons.
3. `stateui-mcp convert`.
4. Start the server and check the apps; `.converted/` still holds the old files.
5. `stateui-mcp convert --purge`.

An app that is not converted keeps its folder; fix what the report names in that app (with the previous release) or rebuild it from parts. The `--statenet` option and Persisted apps (`sync: "persisted"`) are gone with the old store: their state lived in the statenet under `apps.<appId>`, which this version does not read, so convert such an app from its `app.json` (its `$.data` snapshot is read from `state.json`, which a statenet-backed app does not have) or rebuild it.

## Security notes

- **No port.** The server listens on nothing: MCP is on stdio, and it reaches the statenet as a client.
- **The statenet has no authentication.** It listens on loopback only, refuses a `Host` that is not loopback and lets in web pages of the origins it is told (`--allow-origin`) only. Anyone who can reach it can read and change every app's live state; a page of an allowed origin can do what the app's views do. Do not put it on a network without your own authentication in front.
- **The view relay.** The statenet relays a page's emits to the server only, and the server's to the pages, so one page cannot send another the document or a command. The server takes a page's file requests for the app of its namespace only.
- **The embedded endpoint** (`startHttpServer`) binds `127.0.0.1` unless told otherwise. While it is bound to a loopback address, a request whose `Host` is not `localhost`, `127.0.0.1` or `[::1]` is refused (DNS rebinding), and a `POST` with an `Origin` header from another host is refused. It has no authentication of its own: `@punyts/magnetic` embeds it with a `tenant` function that finds the signed-in user's workspace, so each user reaches only their own apps.
- **An app in the page shares the page's origin.** With `?surface=page` the app's expressions run in the page, which therefore allows `'unsafe-eval'`, and the app could reach what the page can: its cookies, its storage and its own server. Use it only for apps the signed-in person owns, as Magnetic's editor does.
- **Apps run code.** An app document can contain binding expressions that run in the sandboxed frame. The frame has no network (`connect-src 'none'`) and no forms. Its origin has its own storage, and it can read cookies that other local servers set for the same host name, but it has no way to send them anywhere except as app events to the server. The headless Chromium is a real browser on your machine: do not point it at documents you do not trust.
- **Paths.** Only UUIDs reach a file path. A file name is metadata and never part of a path.
- **Uploads.** The type is sniffed from the bytes; the type the client claims is ignored. HTML, SVG, XML and executables are refused.
- **3D models (GLB only).** A file is `model/gltf-binary` when it starts with the `glTF` magic number, version 2, and a header length equal to its size (`detectMagicType(head, size)` in `src/domain/UiFile.ts`). A `.gltf` (JSON with external buffers and images, which the frame could not fetch), a GLB cut short, of another version or with a wrong length, and any file named `.glb` or `.gltf` that is not such a GLB are refused with `415 unsupported_type`. `ui_file_read` answers a GLB's reference with `text: null`. The live view's host takes the allowed list from `src/domain/UiFile.ts` itself; `@punyts/stateui-components` keeps a copy, and a test in each library pins both to one literal. The 10 MiB file limit is the model limit: a product model with a few hundred thousand triangles and 1K to 2K textures usually fits, one with several 4K textures or a scanned mesh often does not, and the Draco, Meshopt and KTX2 compression that would shrink it is not supported (G3.7b refuses it). Reduce the texture sizes or the mesh before uploading.

## Develop

```sh
npm run typecheck   # server and browser host script
npm run build       # dist/ (server, Vite plugin) and dist/browser/host.js (the embedded endpoint's host script)
npm test            # Vitest; the Playwright tests skip themselves when Chromium is missing
npm run dev         # the statenet and the view page, for a client that runs the server on stdio
```

`test/statenetBridge.test.ts` drives the server through a real statenet with a page that speaks the protocol by hand; `test/statenet.integration.test.ts` runs the view page on Vite, a statenet, the server and Chromium together, and the command on stdio.

Layout: `src/domain` (pure rules, and the view relay's envelopes), `src/application` (ports and use cases), `src/infrastructure/storage` (the JSON file adapters), `src/infrastructure/mcp` (tools and server), `src/infrastructure/statenet` (the server's side of the views in a statenet), `src/infrastructure/view` (the view page's Vite plugin), `src/infrastructure/http` (the embedded endpoint: routes, pages, policy), `src/infrastructure/preview` (the hub of live views and the Playwright adapter), `src/browser` (the view that runs in the page: `host.ts`, its channels, `statenetView.ts` for the view page and `hostPage.ts` for the embedded endpoint), `view/` (the Vite project of the view page), `src/config` (options and composition), `src/testing` (fixtures and in-memory fakes for tests; not built).

## License

MIT