---
title: Widget reference
summary: The team's widgets and dashboards - the widget contract, the types, each widget's store and settings, host.widgets for the widgets and widgets:view permissions, the widget frame and its spacemix object, widget tokens in messages, and the layout helpers.
audience: both
stability: experimental
since: protocol 1
---

# Widget reference

Widgets are small, user-made views that pull data out of extensions (or, through [web sources](#web-sources), public data from the web) and show it. The assistant writes them when the user asks: an HTML fragment plus the read-only tool calls ("sources") that feed it. They belong to the team, not to any extension: everyone on the server sees and can change every widget and dashboard. Dashboards (the extension) arranges them in grids; Team Chat shows them live inside messages.

A widget runs in a sandboxed frame of its own with no access to the app, and its CSP blocks the requests it would make itself. That doesn't keep its data in: a widget can navigate its own frame and leak what it puts in the URL, and an extension that hosts a widget can load images and media from any URL (see [Known gaps](#known-gaps)). The only data it sees is what its sources return and what it asks for through `spacemix.call`: read-only tools of installed extensions, and web sources with a fixed URL that the server fetches (never through `spacemix.call`). The one thing it can write is [its store](#the-widgets-store): one JSON object of its own on the server, shared by everyone who sees it.

The method-by-method `host.widgets` reference is also in [Widgets API](host/widgets.md); this page adds the types, the widget frame, tokens in messages and the layout helpers.

Sources: `packages/sdk/src/widgets.ts` (types and `WidgetsApi`), `packages/sdk/src/widgetLayout.ts` (grid helpers), `packages/sdk/src/react.ts` (`useWidgetList`, `useWidgetFeed`, `WidgetFrame`, see [React hooks](react.md#usewidgetlist)), and in the app `apps/desktop/src/lib/widgets.ts`, `widgetRuntime.ts`, `src-tauri/src/widget_frame.html` and `src-tauri/src/widget.rs` (the frame's CSP).

## The widget contract

A saved widget is HTML in the database. It is never rebuilt: the same markup and scripts run against whatever widget frame the SpaceMIX release in front of the viewer ships. So the widget frame has a version of its own, `WIDGET_FRAME_VERSION` in `packages/sdk/src/widgets.ts` (today `3`), and a promise of its own:

**A widget saved today keeps rendering on every later SpaceMIX release that speaks its widget frame version or a later one.** Frame 3 (the SpaceMIX rename) is the one exception: saved widgets were carried over by a one-time migration. Within a version the global `spacemix`, its [members](#spacemix-in-the-widget), the `spacemix.ui` helpers with their parameters and options, the `op-*` classes and their modifiers, the attribute hooks (`data-open`, `aria-selected="true"` on `op-tabs`, `aria-pressed="true"` on `op-segmented` and `op-chip`, `data-theme` on the root), the `--op-*` variables and the messages the parent sends the frame only grow. Removing or renaming any of them, or changing what it does, needs a `WIDGET_FRAME_VERSION` bump and a [changelog](../changelog.md) entry, and the new frame must keep widgets made for the earlier versions working. The frame reports the version it speaks as `spacemix.version`.

| Version | What it added |
|---|---|
| `1` | The frame as first versioned: everything on this page but the store. |
| `2` | [The widget's store](#the-widgets-store): `operator.store`, `operator.save` and `operator.onStore`, as the global was called then; the frame → parent message `{ type: "save", id, value, merge }`, answered with `result`; the parent → frame message `{ type: "store", value }` and the `store` field of `render`. Everything in version 1 is unchanged, so widgets made for it run as before. |
| `3` | The rename to SpaceMIX: the global is `spacemix`, with no alias for `operator`, and the frame's marker is `spacemix-widget-frame`. Widgets saved before it are rewritten by a one-off migration; a widget file from before it can't be imported. |

Security is the exception, in both directions:

- **Tightening is allowed at any time.** The [CSP](#the-document), the iframe's sandbox attributes and the limits on navigation may be made stricter for security without a `WIDGET_FRAME_VERSION` bump, with a changelog entry. A widget that relied on what was closed may stop working.
- **Loosening is never additive.** Widening the CSP or the sandbox, and any new message (or message field) from the frame that the parent acts on, opens a new way out of the sandbox. Each needs a security review and a `WIDGET_FRAME_VERSION` bump.

### What the guard checks

`npm run docs:check` (`scripts/check-contract.mjs`) reads the frame's surface into the `widgetFrame` section of `docs/contract/surface.json` and compares it with the snapshot. It reads:

- `apps/desktop/src-tauri/src/widget_frame.html`: the global's name, the `spacemix` members and `spacemix.version`, each `spacemix.ui` helper's parameter names (in order) and the options it reads, the messages the frame posts and handles with their fields (and `theme.mode`, `theme.vars`), the `op-*` classes and modifiers, the attribute selectors and hooks, and the custom properties the kit defines or reads;
- `apps/desktop/src-tauri/src/widget.rs`: the `CSP`, and that the frame is served with it;
- `packages/sdk/src/react.ts` (`WidgetFrame`): the iframe's `sandbox` and `referrerPolicy`, `THEME_VARS`, the theme it sends and the messages it posts and handles; `apps/desktop/src/shell/widgets/WidgetFrame.tsx`, the app's own copy, must match it;
- `apps/desktop/src-tauri/src/server.rs`: each frame document's route (`/api/widget-frame`, `/api/ext-frame`, `/api/ext-page`) appends a `sandbox` policy with the iframe's own flags, keeping the document's own CSP. A failure, not a snapshot field;
- `packages/sdk/src/widgets.ts`: `WIDGET_FRAME_VERSION`, `WIDGET_TOKEN_RE` and the grid constants with their values;
- `apps/desktop/src/lib/widgetTools.ts`: the `spacemix` members, `spacemix.ui` helpers and options, classes, `--op-*` variables and `aria-*`/`data-*` attributes the widget session's prompt names must exist in the frame. Modifiers are read when the prompt writes them as `.op-x.y`, `.op-x [a|b]`, a bare `.y` on a line that names the class, or `class "op-x" or "y"`; other phrasings aren't read.

The frame's surface must be named in this page itself; a mention elsewhere under `docs/reference/` doesn't count. All of it must go through `post({ type: "…", … })`: a `postMessage` anywhere else in the frame's script, or `post` called with anything but an object literal with a literal `type`, fails the check. The iframe's `sandbox` and `referrerPolicy` must each be written once, as a plain string.

The check also fails when one of these safety measures disappears: in the frame, the `event.source !== host` test on incoming messages and the `preventDefault` on link clicks and on `submit`; in both `WidgetFrame`s, the `e.origin !== "null"` test and the stop on the second `load`. It checks only that they are present, not that they are right; review reads them.

A removal or change in any of these fails the check and is refused by `npm run docs:update` unless `WIDGET_FRAME_VERSION` moved; a change to the grid constants or `WIDGET_TOKEN_RE`, which are SDK exports too, also needs `PROTOCOL_VERSION` or the SDK's breaking line to move. A CSP or sandbox change that only tightens passes with `npm run docs:update -- --csp-tightened`; a loosening is refused even then. A new message from the frame to the parent counts as a change, not an addition. `spacemix.version` must equal `WIDGET_FRAME_VERSION`.

**Not covered by the guard**, though still part of the promise: what each helper does and returns (its markup, its defaults such as `empty()`'s text or `donut`'s size, number and date formatting), how the classes look (their CSS values may be tuned), the timing of messages and the 10-second `spacemix.call` limit, and the `postMessage` handling in the frame beyond message types and fields. Reviews check these by hand. Not part of the promise at all: the frame document's structure (the root element `#spacemix-widget-frame`, the `<head>`, the order of the kit's rules), so a widget styles its own classes and ids only.

Stability on this page, part by part:

| Part | Stability | Why |
|---|---|---|
| [The widget frame](#the-widget-frame): the document and its CSP, the messages, `spacemix`, `spacemix.ui`, the `op-*` classes, the `--op-*` variables | stable | Saved widgets depend on it and are never rebuilt. |
| [Grid constants](#grid-constants) | stable | Every saved dashboard's positions and sizes are measured in them. |
| [Widgets in messages](#widgets-in-messages): the token format and `WIDGET_TOKEN_RE` | stable | Tokens are stored in message text for good. |
| [Types](#types) and [`host.widgets`](#hostwidgets) (`WidgetsApi`, `WidgetsViewApi`), including `frameUrl` | experimental | Built for Dashboards and Team Chat and not yet exercised live by other extensions. |
| [The widget's store](#the-widgets-store): the frame's side (`spacemix.store`, `spacemix.save`, `spacemix.onStore`, their messages) | stable | Part of the widget frame, from version 2. |
| The store's types, its limits and `host.widgets.save` | experimental | With `host.widgets`. |
| `useWidgetList`, `useWidgetFeed`, `WidgetFrame` ([React hooks](react.md#usewidgetlist)) | experimental | They follow `host.widgets`. |
| [Layout helpers](#layout-helpers) | experimental | They exist for Dashboards and may move. |

The page as a whole is `experimental`; the parts marked `stable` above are covered by the [contract](../contract.md#stability-labels). `PROTOCOL_VERSION` doesn't cover the widget frame, and `WIDGET_FRAME_VERSION` doesn't cover `host.widgets`.

### Known gaps

These are open, and true today:

- **A widget can navigate its frame and leak what it puts in the URL.** Widgets on Dashboards and in Team Chat cards are shown by extensions, inside an extension frame whose CSP allows `frame-src http: https:`, in the desktop app as well as in the browser. There nothing stops a widget from sending its frame to any URL with its data in it. The stop on the second `load` only limits what happens after; a page that never finishes loading keeps the bridge: it is sent data updates and can `call` any read-only tool of any installed extension, not only the widget's sources, and `save` to the widget's store. Only the frames the shell hosts itself, the Widgets gallery and Studio, are covered: in the desktop app by the app's CSP, whose `frame-src` allows only the app and the widget frame, so there the navigation is blocked; in the browser by the page's CSP, which the server sends with `frame-src 'self'` (`APP_CSP` in `src-tauri/src/server.rs`), so there a frame can go no further than the server's own origin. The planned fix is a widget relay document with a strict `frame-src` between the host and the widget frame.
- **Extension frames load images and media from anywhere.** The extension showing a widget has a frame whose CSP allows images and media from http(s) URLs, with no `net:` permission needed. Whatever it puts in such a URL leaves the server's control. Not tightened yet.
- **WebRTC.** `RTCPeerConnection` isn't governed by the CSP, so a widget may be able to leak data through STUN or DNS lookups in likely every engine. Untested; WebKitGTK probably has WebRTC off.
- **Web sources tell their site about viewing.** The site behind a [web source](#web-sources) sees when, and how often, the widget is viewed (fetches that miss the 30-second shared cache), from the server's address. And `refresh` lets an extension with `widgets:view` make a widget's web sources fetch, which gives it a slow timing channel to that site.
- **The second-`load` rule assumes the iframe's initial `about:blank` fires no `load`** (the spec's behaviour for an iframe created with a `src`). To be verified in WebKitGTK and WebView2; where it does fire, every widget would be stopped as navigated.

## Permissions

| Permission | Gives |
|---|---|
| `widgets` | All of `host.widgets` (`WidgetsApi`): read and change widgets and dashboards, open the Studio and the gallery. `deleteWidget` and `openStudio` also depend on the person using it holding [`server:widgets`](permissions.md#who-may-create-extensions-and-widgets). Dashboards uses it. |
| `widgets:view` | Only `WidgetsViewApi`: the saved widgets (without Studio drafts or history), showing them live, and saving the [store](#the-widgets-store) of a widget the extension shows right now (`save` while it `watch`es that widget). Changes no widget or dashboard, and writes nothing else: `save` is the one method here that writes, and it is held to [the viewer's OK](#the-viewers-ok). Team Chat uses it. |

`host.widgets` is present when the manifest declares either permission. With only `widgets:view`, the methods outside `WIDGETS_VIEW_METHODS` reject with `<name> doesn't have the "widgets" permission.` (see [Permissions](permissions.md)). Widgets made in the Studio are seen by viewers only once saved.

A widget's sources run in the client of whoever is looking, as that person, so two people can see different data in the same widget. Its [store](#the-widgets-store) is the same for everyone.

## Types

```ts
interface WidgetSource {
  key: string;                    // `[a-zA-Z_][a-zA-Z0-9_]*`; the result is spacemix.data[key]
  tool: string;                   // a read-only assistant tool, e.g. "tasks_items_list", or WEB_SOURCE_TOOL ("web-get")
  args: Record<string, unknown>;
  extension?: WidgetExtension;    // where the tool came from, recorded when the source was set
}

interface WidgetExtension { id: string; name: string }

type WidgetSize = { w: number; h: number }; // grid cells

interface Widget {
  id: string;
  name: string;
  description: string;            // one line: what it shows
  sources: WidgetSource[];
  html: string;                   // markup, <style> and <script>, rendered inside the widget frame
  size: WidgetSize;               // size it takes when added to a dashboard
  grid?: number;                  // columns `size` is measured in; absent on widgets from the first, 4-column grid
  refreshSeconds: number;         // how long fetched data stays good in the viewer's cache (at least 30 s); see "The data cache"
  chatId?: string;                // the chat it was made in
  history: WidgetVersion[];       // newest last, at most 10
  draft?: DraftFields;            // changes made in the widget Studio, not saved yet; dashboards and the gallery keep showing the saved widget
  unsaved?: boolean;              // made in the Studio and never saved: not offered for dashboards until it is
  settings?: WidgetSetting[];     // the settings form for its store; part of the widget, like its code
  defaultStore?: WidgetStoreValue; // what its store starts as, before anything is saved
  createdAt: number;
  updatedAt: number;
}

interface WidgetVersion {
  at: number; name: string; description: string; sources: WidgetSource[]; html: string;
  settings?: WidgetSetting[]; defaultStore?: WidgetStoreValue;
}
type DraftFields = Pick<Widget, "name" | "description" | "sources" | "html" | "size" | "refreshSeconds" | "settings" | "defaultStore">;
type WidgetDraft = Pick<Widget, "name" | "description" | "sources" | "html"> & Partial<Pick<Widget, "size" | "refreshSeconds" | "chatId" | "settings" | "defaultStore">>;

interface DashboardItem { id: string; widgetId: string; x: number; y: number; w: number; h: number }
interface Dashboard { id: string; name: string; items: DashboardItem[]; grid?: number; updatedAt: number }
type DashboardBox = Pick<DashboardItem, "id" | "x" | "y" | "w" | "h">;

interface WidgetStatus {
  state: "idle" | "loading" | "ready" | "error";
  error?: string;
  missing?: { id?: string; name: string }[];  // extensions the sources need that aren't installed
  refreshedAt?: number;                       // when the data shown was fetched (by the last run, or earlier from the cache)
  fetching?: boolean;                         // the sources are running right now
}
type WidgetData = Record<string, unknown>;     // by source key; a failed source is { error }
interface WidgetUpdate { status: WidgetStatus; data?: WidgetData; purged?: boolean; store?: WidgetStore }

type WidgetStoreValue = Record<string, unknown>; // a widget's store: a JSON object
interface WidgetStore {
  value: WidgetStoreValue;  // as saved, or the defaults; with each setting's default for a key it lacks
  updatedAt?: number;       // last saved, by the server's clock; absent while nothing has been
  updatedBy?: string;       // the id of the person who saved it last
}
interface WidgetSetting {
  key: string;              // the store's top-level key, `[a-zA-Z_][a-zA-Z0-9_]*`
  label: string;
  type?: "text" | "number" | "switch" | "choice" | "textarea"; // default "text"
  options?: { value: string; label?: string }[];               // for "choice"
  default?: string | number | boolean;
  help?: string;            // one line under the field
}
const MAX_WIDGET_STORE_BYTES = 262_144; // 256 KB of JSON
```

- The exported types are `WidgetSource`, `WidgetExtension`, `WidgetSize`, `Widget`, `WidgetVersion`, `DraftFields`, `WidgetDraft`, `DashboardItem`, `Dashboard`, `DashboardBox`, `WidgetStatus`, `WidgetData`, `WidgetUpdate`, `WidgetStoreValue`, `WidgetStore` and `WidgetSetting`, and the constant `MAX_WIDGET_STORE_BYTES`. `settings`, `defaultStore` and `WidgetUpdate.store` are what [the widget's store](#the-widgets-store) adds. `DraftFields` is what a Studio draft can change; `WidgetDraft` is what creating a widget takes; `DashboardBox` is one item's position and size for `setLayout`.
- `DashboardItem.id` is the placement id: the same widget can sit on a dashboard more than once. `x` and `y` are the column and row of its top-left cell, from 0.
- `WidgetSource.extension` is filled in by the host when a source is set (the assistant's widget tools); widgets made before it have none, and so do [web sources](#web-sources).
- `WidgetStatus.missing` lists the extensions a widget's sources need that aren't installed on the server. An extension that is installed but that the viewer may not use (see [Who can use an extension](permissions.md#who-can-use-an-extension)) isn't listed: its sources get `{ error: "<Name> isn't available to you." }` instead, and the widget renders with that. Neither is a paid extension [turned off until it's paid for](permissions.md#turned-off-until-its-paid-for): its sources get `{ error: "<Name> is turned off on this server until it's paid for." }` for a viewer who may use it, and the `isn't available to you` error for anyone else. An entry without `id` comes from a source with no recorded extension; its `name` is then the tool's namespace (`"tasks"` for `tasks_items_list`). `WidgetFrame` shows it as an "Extension uninstalled" pill in place of the widget.
- `WidgetStatus.error` is a source that failed (`"<key>: <message>"`) or an error the widget's own script threw. Status is live, never stored.
- `WidgetStatus.refreshedAt` is when the data shown was fetched, which may be before the widget came on screen when it came out of the cache; `fetching` is set while the sources run, including a refresh that keeps `state: "ready"` because data is already up. `WidgetUpdate.purged` means the cache was dropped: forget the data shown and wait for the next `data`.

**Stability:** experimental: these are the shapes `host.widgets` returns, which isn't yet exercised live by other extensions.

## Grid constants

```ts
const GRID_COLS = 12;        // columns
const MAX_ROWS = 24;         // tallest a widget can be, in rows
const ROW_HEIGHT = 40;       // px per row
const GRID_GAP = 10;         // px between cells
const MIN_SIZE: WidgetSize;  // { w: 2, h: 2 }
const SIZE_PRESETS: { label: string; size: WidgetSize }[];
// Small 3×3, Medium 4×5, Large 6×8, Wide 12×4, Tall 3×8
```

The exported constants are `GRID_COLS`, `MAX_ROWS`, `ROW_HEIGHT`, `GRID_GAP`, `MIN_SIZE` and `SIZE_PRESETS`. Sizes passed to `resizeItem` and `setLayout` are clamped to `MIN_SIZE` … `GRID_COLS` × `MAX_ROWS`. A new widget defaults to 4×5.

**Stability:** stable. Saved dashboards are measured in these; the grid changed once already (from 4 to 12 columns, see `grid`), and a change like that again would rearrange every dashboard. They are versioned with the widget frame: the guard records their values and refuses a change unless `WIDGET_FRAME_VERSION` moved.

## host.widgets

```ts
interface WidgetsApi {
  widgets(): Promise<Widget[]>;
  dashboards(): Promise<Dashboard[]>;
  snapshot(): Promise<{ widgets: Widget[]; dashboards: Dashboard[]; ready: boolean }>;
  subscribe(fn: () => void): () => void;
  createDashboard(name?: string): Promise<Dashboard>;
  renameDashboard(id: string, name: string): Promise<void>;
  deleteDashboard(id: string): Promise<void>;
  reorderDashboards(ids: string[]): Promise<void>;
  addToDashboard(dashboardId: string, widgetId: string, at?: { x: number; y: number }): Promise<void>;
  removeFromDashboard(dashboardId: string, itemId: string): Promise<void>;
  resizeItem(dashboardId: string, itemId: string, size: WidgetSize): Promise<void>;
  setLayout(dashboardId: string, boxes: DashboardBox[]): Promise<void>;
  deleteWidget(id: string): Promise<void>;
  openStudio(options?: { widgetId?: string; dashboardId?: string; text?: string }): Promise<void>;
  openGallery(widgetId?: string): Promise<void>;
  frameUrl(): Promise<string>;
  watch(widgetId: string, onUpdate: (update: WidgetUpdate) => void): () => void;
  refresh(widgetId: string): Promise<void>;
  purge(widgetId: string): Promise<void>;
  call(widgetId: string, tool: string, args: unknown): Promise<unknown>;
  reportError(widgetId: string, message: string): Promise<void>;
  save(widgetId: string, value: WidgetStoreValue, options?: { merge?: boolean }): Promise<WidgetStore>;
}

type WidgetsViewApi = Pick<WidgetsApi, (typeof WIDGETS_VIEW_METHODS)[number] | "subscribe" | "watch">;
```

Writes change the shared store, which every window, every account and the assistant's `widget_*` tools see. Making and editing widgets themselves happens in the Studio (`openStudio`), not through this API.

Each method is the bridge request `widgets.<method>` (see [Protocol](protocol.md)); `subscribe` and `watch` are the subscription channels `widgets` and `widget-data`. The tables below list them.

```ts
const WIDGETS_METHODS: readonly [
  "widgets", "dashboards", "snapshot", "createDashboard", "renameDashboard", "deleteDashboard",
  "reorderDashboards", "addToDashboard", "removeFromDashboard", "resizeItem", "setLayout",
  "deleteWidget", "openStudio", "openGallery", "frameUrl", "refresh", "purge", "call", "reportError", "save",
];
const WIDGETS_VIEW_METHODS: readonly ["widgets", "frameUrl", "refresh", "purge", "call", "reportError", "openGallery", "save"];
```

### Reading

| Method | Bridge | Permission | Behavior |
|---|---|---|---|
| `widgets()` | `widgets.widgets` | `widgets` or `widgets:view` | Every widget. With `widgets`, unsaved Studio widgets are included (`unsaved: true`) with their `draft` and `history`. With only `widgets:view`, saved widgets only, without `draft` and with an empty `history`. |
| `dashboards()` | `widgets.dashboards` | `widgets` | Every dashboard, in order. |
| `snapshot()` | `widgets.snapshot` | `widgets` | Both at once, and `ready`: whether they've been read from storage yet (until then both are empty). |
| `subscribe(fn)` | channel `widgets` | `widgets` or `widgets:view` | `fn()` whenever widgets or dashboards change, from any window or the assistant. Read again. Returns the unsubscribe. |

### Arranging (`widgets` only)

| Method | Bridge | Behavior |
|---|---|---|
| `createDashboard(name?)` | `widgets.createDashboard` | A new dashboard; a blank or missing name gives "New dashboard". Resolves with it. |
| `renameDashboard(id, name)` | `widgets.renameDashboard` | Blank names are ignored. |
| `deleteDashboard(id)` | `widgets.deleteDashboard` | Its widgets stay; only the arrangement goes. |
| `reorderDashboards(ids)` | `widgets.reorderDashboards` | The dashboards in this order; unlisted ones keep their place after them. |
| `addToDashboard(dashboardId, widgetId, at?)` | `widgets.addToDashboard` | At the widget's own size, in the first free spot, or at cell `at` (integers) pushing what's there down. Rejects a widget that is still `unsaved`; it must be saved in the Studio first. |
| `removeFromDashboard(dashboardId, itemId)` | `widgets.removeFromDashboard` | Takes one placement off. |
| `resizeItem(dashboardId, itemId, size)` | `widgets.resizeItem` | Pushes whatever it now covers down. |
| `setLayout(dashboardId, boxes)` | `widgets.setLayout` | New positions and sizes for some or all items, for example after a drag with the items it pushed. Sizes are clamped. |
| `deleteWidget(id)` | `widgets.deleteWidget` | Deletes the widget everywhere: the gallery and every dashboard. Rejects when the person doesn't hold `server:widgets`, or when the write fails; the widget and its placements then stay. A widget already gone counts as deleted. |

### Leaving the view

| Method | Bridge | Permission | Behavior |
|---|---|---|---|
| `openStudio(options?)` | `widgets.openStudio` | `widgets` | Opens a widget session in a tab of the [Studio](../guide/studio.md): a new widget for `dashboardId`, or `widgetId` to change one. `text` is sent as the first message. Someone else's never-saved widget opens in the Widgets gallery instead, where it is reviewed before it opens in the Studio. It always resolves: for a person without `server:widgets` it shows the Studio's notice that building needs a permission, and no session starts. Leaves your view. |
| `openGallery(widgetId?)` | `widgets.openGallery` | `widgets` or `widgets:view` | Opens the Widgets gallery, scrolled to `widgetId` if given. Leaves your view. |

### Showing a widget

| Method | Bridge | Permission | Behavior |
|---|---|---|---|
| `frameUrl()` | `widgets.frameUrl` | `widgets` or `widgets:view` | The widget frame document's absolute URL for this window. The extension frame's CSP allows it. |
| `watch(widgetId, onUpdate)` | channel `widget-data` | `widgets` or `widgets:view` | See [watch](#watch). |
| `refresh(widgetId)` | `widgets.refresh` | `widgets` or `widgets:view` | Fetches the widget's sources again now, if it is on screen anywhere in this window. What's shown stays up until the results are in, and the cache takes them. A widget that is still `unsaved` rejects with `This widget isn't saved yet.` |
| `purge(widgetId)` | `widgets.purge` | `widgets` or `widgets:view` | Drops the viewer's cached data for the widget (every window of theirs). Watchers get `{ purged: true }`; on screen, the widget goes back to loading and fetches afresh. For a widget that is still `unsaved` it resolves and does nothing. |
| `call(widgetId, tool, args)` | `widgets.call` | `widgets` or `widgets:view` | `spacemix.call` on the widget's behalf. A widget that is still `unsaved` rejects with `This widget isn't saved yet.` See [call](#call). |
| `reportError(widgetId, message)` | `widgets.reportError` | `widgets` or `widgets:view` | The widget's own script threw. The message (cut to 1,000 characters) shows in its status until its code changes. For a widget that is still `unsaved` it resolves and does nothing. |
| `save(widgetId, value, options?)` | `widgets.save` | `widgets` or `widgets:view` | Saves the widget's [store](#the-widgets-store): replaces it with `value`, or with `{ merge: true }` puts `value`'s top-level keys over it (a `null` removes that key). Resolves with the `WidgetStore` after. Answers the frame's `spacemix.save`, with [the viewer's OK](#the-viewers-ok) where that's needed; also for a settings panel. With only `widgets:view`, only for a widget this frame is watching right now (`watch`), else it rejects with `<Name> can change a widget's data only while it shows that widget.`; with `widgets`, any saved widget. Rejects when `value` isn't an object or is over `MAX_WIDGET_STORE_BYTES`, with `This widget isn't saved yet.` for a widget that is still `unsaved`, and with `This widget no longer exists.` Changes nothing of the widget itself. |

**Errors:** a missing or non-string id rejects with `The id must be a string.`; a method outside your permission rejects with the permission error. `deleteWidget` also rejects with `You don't have permission to create widgets on this server.` when the person doesn't hold `server:widgets`, and with `The server didn't delete the widget.` when the write fails.

**Stability:** experimental: built for Dashboards and Team Chat and not yet exercised live by other extensions (see [Widgets API](host/widgets.md#stability)).

### watch

```ts
watch(widgetId: string, onUpdate: (update: WidgetUpdate) => void): () => void;
```

Keeps the widget's sources running while watched, shared with every other place in the window showing the same widget, and delivers its status and data: right away if known, then on every change. `data` comes whenever the sources ran or their cached results came in; a status-only update has no `data`; `purged: true` means the cache was dropped (forget the data shown). `store` (widget frame 2) comes once the widget's store has been read and again whenever it changes, from anywhere; an update without it keeps the store shown, and a purge doesn't touch it. The widget's current definition is used, so a change in the Studio re-runs it on its own. A widget that is still `unsaved` doesn't run: it gets an error status (`This widget isn't saved yet.`) with `purged: true`, also when a saved widget turns unsaved, and starts once it's saved. Returns the unsubscribe.

When the sources run:

- when the first watcher starts and the cache has nothing fresh for the widget (see below),
- when the cached data expires (`refreshSeconds` after it was fetched, at least 30 s) while the window is visible, and on coming back to the window if that passed while hidden,
- shortly after the data of an extension the widget reads changes, here or in another window (debounced 400 ms),
- on `refresh`, after `purge`, and when the sources change.

Each source has 15 seconds. A source that fails, or names a tool that isn't a read-only tool of an installed extension (or a [web source](#web-sources)), gets `{ error }` under its key, and the status says which. A source whose extension is installed but not available to the viewer gets `{ error: "<Name> isn't available to you." }`, or `{ error: "<Name> is turned off on this server until it's paid for." }` when the viewer may use it but it is turned off until it's paid for. When data is already up, a failed run leaves it up and only the status changes.

A widget that doesn't exist, or is deleted while watched, reports `{ status: { state: "error", error: "This widget no longer exists." } }` once (with `purged: true` if it was deleted), and a deleted widget's sources stop.

### The data cache

What a widget's sources return is cached per viewer (the sources run as whoever is looking), in memory and in the core's `widgetcache` namespace, with the time it was fetched. A widget coming on screen shows the cached results at once, with `status.refreshedAt` the time they were fetched, and fetches again only once they are older than its `refreshSeconds`. So a widget whose sources are heavy (an external API, a big list) costs one fetch per lifetime, not one per dashboard visit or page load, as long as the assistant gives it a lifetime to match. A widget made without one keeps its data for a day (86400 s).

- The cache is keyed by the widget's sources: changing them drops it; changing only the HTML keeps it.
- Only a run in which every source succeeded is cached. An entry larger than 1 MB as JSON stays in memory for the session and isn't stored.
- A window of the same person's that fetches or purges a widget's data is heard by the others, which take the newer data rather than fetching too.
- When a source's extension is no longer installed, the cached data is dropped rather than shown, and the widget shows the missing-extension pill (`status.missing`). When it is installed but the viewer may no longer use it, or it is turned off until it's paid for, the cached data is dropped too and the source shows its error. When the extension is turned on again, widgets on screen run their sources again.
- `refresh` fetches again while the data shown stays up; `purge` drops the entry and starts over from loading. Dashboards offers both from the dropdown in a widget's top-right corner; the Widgets gallery from a widget's menu.

### call

```ts
call(widgetId: string, tool: string, args: unknown): Promise<unknown>;
```

Runs `tool` as the person looking and resolves with its result. Only read-only tools of installed extensions qualify: collection `list` and `get`, actions declared `readOnly`, and MCP tools annotated `readOnlyHint: true`; never the core's own `widget_*` tools, and never `web-get`, which rejects with `web-get can't be called from a widget's script; web data comes only from the widget's sources, whose URLs are fixed when it's made.` Arguments are validated like the assistant's. Rejects with `"<tool>" isn't a read-only tool of an added extension.`, with the tool's own error, or after 10 seconds.

### Web sources

```ts
const WEB_SOURCE_TOOL = "web-get";
function widgetWebHosts(sources: WidgetSource[]): string[];

// e.g.
{ key: "btc", tool: "web-get", args: { url: "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd" } }
```

A source whose `tool` is `WEB_SOURCE_TOOL` brings public data from the web without giving the widget any network: when someone views the widget, the server fetches `args.url`, anonymously (nothing of the viewer goes out, only the URL), and the result arrives in `spacemix.data[key]` like any other source's. The widget frame, its CSP and `spacemix` don't change. `web-get` is a marker, not a tool: tool names of extensions and MCP servers always contain an `_` and this has none, so none can take it.

- **Only as a declared source, approved.** The URL is fixed when the source is set, and the person approves every URL a `widget_create` or `widget_update` call adds or changes, shown in full, before anything fetches it; a call that leaves the URLs as they are doesn't ask. The URL is stored, shown for approval, matched and fetched in one normalized form, the parsed URL written out (`new URL(url).href` without its fragment: a lower-case host, punycode for an international name, `\` as `/`); an international host is called out in the approval (`(international address: <host> uses non-ASCII letters; check it is the site you expect)`) so a look-alike stands out. `spacemix.call` (and `host.widgets.call`) refuse `web-get`, so a widget's script can never pick a URL, or put other sources' data into one.
- **Only a widget's URL.** The server fetches a URL only when some widget in the server's widget store has it as a web source (saved, or in a Studio draft), both compared in the normalized form; anything else is refused with `That URL isn't a web source of any widget on this server.` Each person gets at most 300 requests a minute to the endpoint, counted first for every request whatever becomes of it (refused, from the cache or fetched), and at most 60 fetches a minute that miss the server's cache and go out. Over either limit the answer is `Too many web sources fetched in the last minute. Try again in a minute.` (status 429), which isn't a row of the egress log.
- **The rules**, on the first request and on every redirect (at most 3): `GET` only; `https:` on the default port, without a user name or password, with whitespace trimmed from both ends and none allowed inside, and no control or format character (zero-width, bidi, U+FEFF) anywhere (parsers drop or rewrite them, or an approval can't show them; percent-encode them), at most 2,048 characters; nothing from the widget but the URL (no headers, cookies or credentials; the server sends only `Accept: application/json, text/plain;q=0.9` and a SpaceMIX user agent). The host must resolve to public addresses only: loopback, private, link-local, unique-local, CGNAT (`100.64.0.0/10`), multicast, broadcast, unspecified and documentation addresses (IPv4 and IPv6, IPv4-mapped included) are refused, and the connection goes to the checked addresses. 10 seconds, at most 1 MB.
- **The result** of a `2xx` answer is the parsed JSON for a JSON type, the text for a `text/*` type (JSON, else the text, when none is given). Anything else is `{ error }` naming the host, for example `api.coingecko.com answered 429.`, `api.example.com can't be reached from web sources.` (a private host and one that doesn't resolve get the same sentence) or `Widgets aren't allowed to reach the network on this server.`
- **Shared briefly.** The server keeps an answer 30 seconds per exact URL for everyone, so many viewers of one dashboard ask the public API once; the viewer's own [data cache](#the-data-cache) and `refreshSeconds` apply on top.
- **Data leaving.** Every hop that goes out (the first request and each redirect) and every refusal is a row of the server's egress log under the id `core.widgets` ("Widgets"); an answer from the 30-second cache and a 429 aren't. A URL the rules refuse, one no widget declares and a host with a private address (or none) are logged as refused `not-declared`, the switch as `network-off`; a refusal has a row only when the string parses as a URL with a host (one that doesn't, or a request refused because the widgets couldn't be read, leaves none). The network switch for that id (`shell/networkBlockedExtensions`) turns every web source off. See [What the server logs, and the network switch](host/net.md#what-the-server-logs-and-the-network-switch).
- **Made by the assistant.** The widget tools check `args.url` against the rules above (except the address check, which is the server's) and allow at most 5 web sources per widget; no `extension` is recorded on them, and a web source is never reported as a missing extension. What a web source returned goes back to the model marked as untrusted content from that site.
- `widgetWebHosts(sources)` lists the hostnames a widget's web sources reach, once each and in order, so a host can show a "Web" tag with them next to the widget's title.

Endpoint: `POST /api/widgets/fetch` `{ url }` → `{ result }` for anyone signed in, IPC `widgets_fetch` in the desktop app (`apps/desktop/src-tauri/src/widget_net.rs`; client `webSourceFetch` in `apps/desktop/src/lib/net.ts`). Server surface, not extension surface.

**Stability:** experimental, with [`host.widgets`](#hostwidgets).

## The widget's store

Each saved widget has one JSON object of its own on the server, its **store**: data the widget saves (a checklist's ticks, a note, a choice) and the values of its [settings](#settings). The widget reads it as `spacemix.store` and writes it with `spacemix.save`; extensions that host the frame answer that with `host.widgets.save`. A widget can't make tables or keep anything else.

- **One per widget per server, shared.** Everyone who can see the widget sees the same store, whoever saved it. Last write wins; the server stamps `updatedAt` and `updatedBy` (`WidgetStore`).
- **The viewer's OK.** See [The viewer's OK](#the-viewers-ok).
- **Who may write it.** Anyone who may view the widget: any signed-in member of the server (widgets are the team's), from the widget's own UI, its settings panel, an extension with `widgets` (any widget) or `widgets:view` (only a widget its frame is showing, that is watching, at the time), or the assistant's `widget_store_set` (with the person's approval). The watch rule stops an extension writing in the background; it isn't a boundary against a malicious one, which can watch any widget. Granting `widgets:view` trusts the extension with the widgets' data. The server enforces the split: the store is a row of its own (the core table `widget_stores`, under the widget's id), written only through the records operation `widgetStoreSet` (`apps/desktop/src-tauri/src/widget_store.rs`), which writes nothing but that row; every other write to the table is refused (`A widget's store changes only through widgetStoreSet.`). So saving a store never changes a widget's code, sources, settings form or defaults.
- **Limits, checked by the server.** A JSON object, at most `MAX_WIDGET_STORE_BYTES` (256 KB) as JSON, for a widget that exists and is saved, and at most one write per widget every 200 ms, whoever writes. Two viewers saving at the same moment can meet that limit; the app then tries again, twice, 250 ms apart, so both writes land and the later one wins. Otherwise the write is refused: `A widget's store must be a JSON object.`, `The store would be <n> KB; a widget's store holds at most 256 KB.`, `This widget no longer exists.`, `This widget isn't saved yet.` or `This widget's data was saved a moment ago; try again.`
- **Replace or merge.** A save replaces the store with `value`; with `merge` it puts `value`'s top-level keys over the current store (a `null` removes that key), which is what the settings form and a checklist's tick want. A merge into a store that was never saved starts from the defaults, and stores them: from then on they are part of the store, so a later change to `defaultStore` doesn't reach it. A `null` for a key that has a setting resets it to the setting's `default`.
- **Defaults.** Before anything is saved the store is the widget's `defaultStore` (or `{}`), and the `default` of each [setting](#settings) fills in a key the store doesn't have, then and later (so a setting added afterwards shows its default).
- **Throttled.** A window sends at most two writes a second per widget; saves in between are folded into the next write (a later replace wins over what's queued, a merge goes on top), and each resolves with that write's result.
- **Live.** A write reaches every frame, window and viewer showing the widget through the change feed; the frame calls `spacemix.onStore` with it and `watch` delivers it as `WidgetUpdate.store`.
- **Not part of the widget.** The store isn't in the widget's version history (restoring a version keeps the data), isn't copied by Duplicate, and isn't in an exported widget file: on another server the widget starts from its defaults. Deleting the widget deletes its store.
- **In the Studio.** A widget that has never been saved keeps its store in the window that's making it until the Studio saves it; then it is written. The preview of a saved widget's draft (`<id>~draft`) uses a copy: it starts from the saved widget's real store, but what the preview saves stays in that window and never reaches the real store. Saving the draft (the widget's code) doesn't write the copy, and saving or discarding the draft drops it.


### The viewer's OK

A store is read by everyone who sees the widget, and a widget's sources and `spacemix.call` run as the viewer. So a frame could read what only this viewer may read and save it where others can see it. To stop that without a review of every widget:

- A window is **tainted** once any widget frame in it has held data from a tool that isn't a [web source](#web-sources): the widget has a tool source, or it called a tool with `spacemix.call`. It's the window, not the frame, because frames in one window can `postMessage` each other. It lasts as long as the window.
- In a tainted window, a `spacemix.save` or `host.widgets.save` needs that viewer's OK for the saving widget's code. The code is the hash of its `html` and `sources`, so changing either asks again. The OK is kept per person on the server (`personal/widgetSaveOk`), which frames can't reach.
- The save waits seven seconds for the answer, then rejects with `This widget is waiting for your OK to save data. Try again once you've answered.`, and the question stays up. A no rejects with `You chose not to let this widget save data.` and isn't asked again until the window reloads. Neither shows as the widget's script error. Catch the rejection and tell the person.
- A window with only web data or none isn't asked. Nor are the widget's settings panel or the assistant's `widget_store_set`, where the person is acting, or a Studio preview, which writes nothing to the server. What a never-saved widget saved in its Studio window is asked about when it first goes to the server, once the widget is saved.

Each person can also save at most 120 times a minute across all widgets; the server rejects more with `Too many widget saves in the last minute; try again shortly.`
### Settings

A widget may declare `settings`, the fields of a form the settings panel draws for its store (with a raw JSON view of the whole store for the rest). Each field reads and writes the store's top-level key `key`:

| `type` | Field | `default` |
|---|---|---|
| `"text"` (or none) | a line of text | a string |
| `"textarea"` | several lines | a string |
| `"number"` | a number | a number |
| `"switch"` | on or off | `true` or `false` |
| `"choice"` | one of `options` (`{ value, label? }`) | one of the options' values |

`label` is the field's caption and `help` a line under it. At most 30 fields with distinct keys. The settings and `defaultStore` are part of the widget, changed like its code (in the Studio or with `widget_update`), kept in its history and carried in a widget file; viewers change only the values.

**Stability:** the frame's side (`spacemix.store`, `spacemix.save`, `spacemix.onStore` and their messages) is stable, versioned by `WIDGET_FRAME_VERSION` 2. The types and `host.widgets.save` are experimental, with [`host.widgets`](#hostwidgets).

## The widget frame

`WidgetFrame` (see [React hooks](react.md#widgetframe)) does everything in this section for you. Read it to write widget HTML, or to host the frame yourself.

Everything in this section is **stable** and versioned by `WIDGET_FRAME_VERSION`; see [The widget contract](#the-widget-contract). Hosting the frame yourself, rather than through `WidgetFrame`, relies on `host.widgets.frameUrl()`, `watch` and `call`, which are experimental.

### The document

The frame is an `<iframe sandbox="allow-scripts allow-forms" referrerpolicy="no-referrer" src={await host.widgets.frameUrl()}>` nested in your extension's frame. Its document holds no data and is served with its own CSP, which allows no network at all:

```
default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; form-action 'none'; base-uri 'none'
```

Over HTTP (`/api/widget-frame`) a second policy is sent with it, `sandbox allow-scripts allow-forms`, so the document is sandboxed whoever loads it, opened directly or embedded without the attribute (`sandboxed` in `src-tauri/src/server.rs`). The desktop app's `spacemix-widget:` scheme doesn't send it.

So a widget's HTML may use inline `<style>` and `<script>` and `data:` or `blob:` images and `data:` fonts, and nothing else. Links don't navigate and forms don't submit: the frame cancels every click on a link and every `submit` (`allow-forms` is there only so a `<form>` still fires `submit`, for Enter in an `op-input`), and `form-action 'none'` stops `form.submit()` too. Scripts in the HTML run in order after it is inserted.

A widget must not navigate its frame. The parent renders only after the frame document's first `load`; a `load` after that means the frame went somewhere else, and the parent stops posting to it, ignores what it sends, takes the frame down and reports `The widget navigated away from its frame, so it was stopped.` as the widget's error. The parent also drops any message whose origin isn't the opaque `"null"`. This contains a widget that navigates, but doesn't make navigating safe where the extension frame allows `frame-src http: https:`: what a widget puts in the URL it navigates to has left by then, and the page it lands on runs in the same sandbox (origin `"null"` too) until its `load` arrives, which it may never do. See [Known gaps](#known-gaps).

### Messages

The widget frame speaks a small protocol of its own, not the extension protocol, over `postMessage`. Its origin is opaque, so only its `window` identifies it, and the parent must post to it with `targetOrigin` `"*"` (an opaque origin can't be named). `ready` is informational: render on the frame's first `load` (see above).

| Direction | Message | When |
|---|---|---|
| frame → parent | `{ type: "ready" }` | Once its script has run. |
| frame → parent | `{ type: "call", id, tool, args }` | `spacemix.call`. Answer with `{ type: "result", id, result }` or `{ type: "result", id, error }` (use `host.widgets.call`). |
| frame → parent | `{ type: "open", id }` | `spacemix.open` or a click on `data-open`: show extension `id` (use `host.shell.open`). |
| frame → parent | `{ type: "error", message }` | The widget's script threw, or a promise was rejected unhandled (use `host.widgets.reportError`). |
| frame → parent | `{ type: "save", id, value, merge }` | Version 2: `spacemix.save`. `value` is an object, `merge` true or false. Answer with `{ type: "result", id, result }`, `result` being the store after (`WidgetStore.value`), or `{ type: "result", id, error }` (use `host.widgets.save`). |
| parent → frame | `{ type: "render", html, data, theme, store }` | Once, after the frame's first `load`, when data is in (and, from version 2, the store: `store` is `WidgetStore.value`). Replaces the content, sets `spacemix.store` and runs its scripts. |
| parent → frame | `{ type: "data", data }` | On every later update. |
| parent → frame | `{ type: "theme", theme }` | When the theme changes. |
| parent → frame | `{ type: "store", value }` | Version 2: the store changed (`value` is `WidgetStore.value`). The frame ignores one equal to the store it has, so the answer to its own save doesn't count as news. |

`theme` is `{ mode: "light" | "dark", vars: { "--op-bg": "…", … } }`, read off the document's tokens: `--op-bg`, `--op-surface`, `--op-elevated`, `--op-fg`, `--op-muted`, `--op-subtle`, `--op-border`, `--op-border-strong`, `--op-accent`, `--op-accent-soft`, `--op-accent-fg`, `--op-danger`, `--op-hover`, `--op-danger-soft`, `--op-success`, `--op-success-soft`, `--op-warning`, `--op-warning-soft`, `--op-info` and `--op-info-soft` (`THEME_VARS` in `packages/sdk/src/react.ts`). Only `--op-*` names are applied. The frame sets `data-theme` on its root to `mode`, so `:root[data-theme="dark"]` matches in dark mode, and defines the status colors itself for a parent that doesn't send them: `--op-success`, `--op-warning` and `--op-info` in light and in `[data-theme="dark"]`, and each `-soft` tint as 12% of its color.

A parent ignores message types and fields it doesn't know, and so does the frame. New messages and fields from the parent to the frame may be added within a version; new ones from the frame that the parent acts on may not (see [The widget contract](#the-widget-contract)). A parent from before version 2 doesn't answer `save`, so `spacemix.save` times out there. The other way round, the SDK's `WidgetFrame` (version 2) on a host from before the store waits 2 seconds for a store that never comes, then renders with `spacemix.store` `{}`; the shell's own frame does the same if reading the store stalls, rendering with the widget's defaults, and sends the store with `{ type: "store", value }` once it arrives.

### `spacemix` in the widget

The widget's scripts get a global, read-only `spacemix`:

| Member | What it does |
|---|---|
| `spacemix.onData(fn)` | Calls `fn(data)` now (if rendered) and after every refresh. Returns an unsubscribe. Always render from this; never assume data is there at load. A throw inside `fn` is reported as a script error. |
| `spacemix.data` | `{ [key]: result }`: each source's JSON result, exactly what the tool returns (a `*_list` tool gives `{ total, items }`). A failed source is `{ error }`. |
| `spacemix.call(tool, args)` | Runs another read-only tool. Resolves with its result; rejects with its error or after 10 seconds. |
| `spacemix.open(extensionId)` | Shows that extension. `data-open="<extension id>"` on any element does the same on click, unless a handler calls `preventDefault`. |
| `spacemix.theme` | `"light"` or `"dark"`. |
| `spacemix.ui` | The widget kit's helpers. |
| `spacemix.store` | Version 2: the widget's [store](#the-widgets-store), an object, set before the widget's scripts run (like `spacemix.data`) and after each save or change. A copy: changing it saves nothing. |
| `spacemix.save(value, { merge }?)` | Version 2: saves the store. Replaces it with `value` (an object), or with `{ merge: true }` sets only its top-level keys (`null` removes one). Resolves with the store after (also `spacemix.store` by then); rejects with the reason (not an object, over 256 KB, not allowed, [waiting for the viewer's OK](#the-viewers-ok)) or after 10 seconds. Saves are folded into at most two writes a second. |
| `spacemix.onStore(fn)` | Version 2: calls `fn(store)` whenever the store changes other than by this frame's own save: another viewer, another window, the settings panel, the assistant. Not called at once (read `spacemix.store`). Returns an unsubscribe. A throw inside `fn` is reported as a script error. |
| `spacemix.version` | The widget frame version this document speaks: `3`, the `WIDGET_FRAME_VERSION` it was built with.  Every frame since the rename is at least `3`, so a widget using `spacemix` has the store. |

`spacemix.ui`:

| Helper | Returns |
|---|---|
| `` html`…${v}…` `` | Markup with every interpolated value escaped (arrays joined; helpers and nested `html` pass through). |
| `raw(s)`, `esc(v)` | Trusted markup that `html` passes through; an escaped string. |
| `render(target, content)` | Sets an element's (or a selector's) content to `html` output, a string, or an array of them. |
| `num(n, { compact?, decimals? })`, `pct(part, whole)` | `1,234` or `12K`; `"42%"`. Non-numbers give `–`. |
| `ago(at)`, `date(at, options?)` | "just now", "5m ago", "3h ago", "2d ago", then a date; a short date. Take ms, an ISO string or a `Date`. |
| `duration(ms, { units? })` | A length of time from milliseconds: `90061000` → `"1d 1h"`, `45000` → `"45s"`. From the largest unit that isn't 0 (`d`, `h`, `m`, `s`), at most `units` of them (default 2), leaving out zeros after the first; the sign is ignored. `0` gives `"0s"`, a non-number `–`. |
| `color(i)` | The i-th series color, `var(--op-c1)` … `var(--op-c6)`. |
| `failed(result)` | The source's error message, or `null`. |
| `empty(text?)`, `error(result)` | A quiet empty state; an error state. |
| `progress(fraction, { color? })` | A meter for 0–1. |
| `bars(values, { max?, height?, color? })` | Vertical bars from numbers or `{ label, value, color }`. |
| `hbars(items, { max?, format? })` | Labelled horizontal bars. |
| `spark(values, { height?, color?, area? })` | A trend line. |
| `donut(parts, { size?, thickness?, legend?, format?, center? })` | Parts of a whole, with a legend. |
| `line(series, { height?, min?, max?, labels?, legend?, area?, color? })` | A line chart. `series` is numbers (one line) or `[{ label, values, color }]` (one line each, over the same x positions). `height` in px (else it fills its container, at least 48 px), `min` and `max` the value range (default the data's), `labels` the x axis (at most 7 shown; more are thinned to 5), `legend` (default with more than one series), `area` a fill under each line (default for one line only), `color` the color of a single line (default `var(--op-accent)`; series get `color(i)` unless they set their own). |
| `gauge(fraction, { size?, thickness?, color?, center?, label? })` | A half ring for 0–1 (clamped). `size` in px (default 120), `thickness` (default 10), `color` (default `var(--op-accent)`), `center` the text in the middle (default the percentage), `label` a line under it. |
| `heatmap(values, { columns?, max?, color? })` | A grid of cells shaded by value, from numbers or `{ label, value }` (the label goes in the cell's tooltip). `columns` (default 7, a week per row), `max` the value of a full cell (default the largest, at least 1), `color` (default the accent). A cell at 0 is empty; others shade from 20% to 100%. |
| `meter(parts, { max?, legend?, format? })` | Parts side by side in one bar, from `[{ label, value, color }]` (each part gets `color(i)` unless it sets one). `max` the whole bar (default the total), `legend: false` leaves the legend out, `format(value)` formats the legend's numbers (default `num`). |
| `avatar(name, { color?, size? })` | Initials (first and last word, or the first two letters) in a circle, colored by the name, with the name as its tooltip. `size` is `"sm"` or `"lg"`; `color` overrides the color. |

**Colors for `line`, `gauge`, `heatmap`, `meter` and `avatar`** (their `color` option and a series' or part's `color`) must be a theme variable written as `var(--op-…)`, such as `"var(--op-success)"`, or a hex color (`#` and 3 to 8 hex digits). Anything else is ignored and the default is used. The older helpers (`bars`, `spark`, `donut`, `progress`) take their colors as before.

The document also has the widget kit's CSS classes (all prefixed `op-`): layout (`op-widget`, `op-scroll`, `op-hstack`, `op-vstack`, `op-between`, `op-grow`, `op-grid`, `op-divider`), boxes (`op-card`, a bordered box for a group of things, clickable as a `<button>`, an `<a>` or with `data-open`; `op-toolbar`, a wrapping row of controls in which an `op-input` or `op-select` takes only its share), text (`op-title`, `op-label`, `op-muted`, `op-subtle`, `op-small`, `op-num`, `op-mono`, `op-truncate`, `op-clamp`, `op-link`), time (`op-clock`, a big tabular time you update from a timer; `op-countdown`, a row of `<div><b>02</b><span>days</span></div>` cells), stats (`op-stat`, `op-stat-value`, `op-stat-label`, `op-delta`), lists (`op-list`, `op-item`, `op-item-title`, `op-item-meta`, `op-dot`, `op-check`), people (`op-avatar`, initials or an `<img>` in a circle; `op-avatars`, an overlapping row of them), `op-timeline` (an `<ol>` whose `<li>`s each start with an `op-dot`, joined by a line), `op-kv` (a `<dl>` of `<dt>` labels on the left and `<dd>` values on the right), `op-table`, `op-badge`, `op-button`, `op-chips` with `op-chip` (filter chips; a chip may end in a small `<button>` that removes it), `op-segmented` (a row of `<button>`s sharing its width, like `op-tabs`), `op-tabs`, form controls (`op-input`, `op-select` on a `<select>`, `op-textarea`, `op-field` as a `<label>` around a caption and its control, `op-checkbox` and `op-radio` on native inputs, `op-switch` on a checkbox), `op-progress`, `op-meter`, `op-gauge`, states (`op-empty`, `op-error`, `op-skeleton`, `op-spinner` while a `spacemix.call` runs, `op-callout`, a tinted note whose first `<svg>` takes the tone), and the charts `spacemix.ui` builds (`op-bars`, `op-hbars`, `op-hbar`, `op-spark`, `op-donut`, `op-legend`, `op-line` with its x-axis row `op-line-x`, `op-heatmap`), which a widget may also style or target.

Modifiers, used together with the class they modify:

```css
.op-widget.tight   .op-widget.center                  /* less padding; everything centred */
.op-stat.lg        .op-stat.sm                        /* a bigger or smaller .op-stat-value */
.op-delta.up       .op-delta.down                     /* --op-success, --op-danger */
.op-dot.ok  .op-dot.warn  .op-dot.danger  .op-dot.info  .op-dot.muted
.op-check.done                                        /* a ticked .op-check */
.op-badge.accent  .op-badge.ok  .op-badge.warn  .op-badge.danger  .op-badge.info  .op-badge.outline
.op-button.primary  .op-button.ghost  .op-button.danger  /* .primary.danger is a solid danger button */
.op-button.sm       .op-button.icon                   /* smaller; square, for an inline <svg> */
.op-table .right                                      /* a right-aligned cell, like .op-num */
.op-card.flat                                         /* no border, on --op-hover */
.op-clock.lg       .op-clock.sm
.op-avatar.sm      .op-avatar.lg
.op-kv.left                                           /* values on the left too */
.op-progress.ok  .op-progress.warn  .op-progress.danger  .op-progress.info
.op-legend.row                                        /* entries in a wrapping row */
.op-callout.accent  .op-callout.info  .op-callout.ok  .op-callout.warn  .op-callout.danger
```

`op-tabs` is a row of `<button>`s; the one with `aria-selected="true"` is the current tab. In an `op-segmented` the current `<button>` has `[aria-pressed="true"]` (or `aria-selected="true"`), and an `op-chip` with `aria-pressed="true"` is a filter that is on; set and clear the attribute from your script. An `op-item`, an `op-table` row or an `op-card` with `data-open` is clickable.

The `ok` and `warn` modifiers (on `op-dot`, `op-badge`, `op-progress`, `op-callout`) and `op-delta.up` use the status colors `--op-success` and `--op-warning`; before, they used the series colors `--op-c2` and `--op-c3`. `info` uses `--op-info`, `danger` `--op-danger`.

Colors are the theme variables above plus the series colors `--op-c1`, `--op-c2`, `--op-c3`, `--op-c4`, `--op-c5` and `--op-c6` (`--op-c1` is the accent), and the status colors `--op-success`, `--op-warning`, `--op-info` and `--op-danger` with their tints `--op-success-soft`, `--op-warning-soft`, `--op-info-soft` and `--op-danger-soft`. Use a status color for text, icons and dots, and its `-soft` tint for a background behind that text, as `op-badge` and `op-callout` do; don't put white text on a solid status color. More custom properties tune a kit piece when set on it: `--min` (the narrowest column of an `op-grid`, default `110px`), `--h` (the height of `op-bars`, `op-spark` and `op-line`), `--color` (the fill of an `op-progress` bar, of `op-bars`, of an `op-meter` part, of an `op-heatmap` cell, the color of an `op-avatar` and of an `op-legend` swatch), `--cols` (the columns of an `op-heatmap`, default 7) and `--level` (how full an `op-heatmap` cell's color is, a percentage; `ui.heatmap` sets both).

A minimal widget for the source `{ key: "tasks", tool: "tasks_items_list", args: { where: { done: false }, limit: 50 } }`:

```html
<div class="op-widget">
  <div class="op-stat sm"><div class="op-stat-value" id="n">–</div><div class="op-stat-label">open tasks</div></div>
  <ul class="op-list op-scroll" id="list"></ul>
</div>
<script>
  const { html, render, ago, empty, error, failed } = spacemix.ui;
  spacemix.onData(({ tasks }) => {
    if (failed(tasks)) return render(".op-widget", error(tasks));
    render("#n", tasks.total);
    render("#list", tasks.items.length
      ? tasks.items.map((t) => html`<li class="op-item" data-open="ai.spacemix.tasks"><span class="op-item-title">${t.title}</span><span class="op-item-meta">${ago(t.updatedAt)}</span></li>`)
      : empty("Nothing open."));
  });
</script>
```

A checklist that saves its ticks (no sources; `settings` `[{ key: "title", label: "Title", default: "Today" }]`, `defaultStore` `{ items: ["Standup", "Review PRs"], done: [] }`):

```html
<div class="op-widget"><div class="op-title" id="t"></div><ul class="op-list op-scroll" id="list"></ul><div class="op-muted" id="note"></div></div>
<script>
  const { html, render } = spacemix.ui;
  const draw = (s) => {
    render("#t", s.title);
    render("#list", (s.items || []).map((item, i) => html`<li class="op-item"><label class="op-hstack"><input type="checkbox" class="op-checkbox" value="${i}" ${(s.done || []).includes(i) ? "checked" : ""}><span class="op-item-title">${item}</span></label></li>`));
  };
  draw(spacemix.store);
  spacemix.onStore(draw);
  document.getElementById("list").addEventListener("change", (e) => {
    const i = Number(e.target.value);
    const done = (spacemix.store.done || []).filter((x) => x !== i).concat(e.target.checked ? [i] : []);
    spacemix.save({ done }, { merge: true }).catch((err) => {
      render("#note", `Not saved: ${err.message}`);
    });
  });
</script>
```

**Stability:** stable: versioned by `WIDGET_FRAME_VERSION` (see [The widget contract](#the-widget-contract)), not by `PROTOCOL_VERSION`.

## Widgets in messages

A widget placed in a message (Team Chat, for one) is written into the message text as a token, `<widget:ID|Name>`. The name is a fallback for wherever the widget can't be shown live: notifications, search, a deleted widget, readers without a widget permission. Viewers with `widgets` or `widgets:view` see the widget live, with their own data.

```ts
const WIDGET_TOKEN_RE: RegExp;  // /<widget:([A-Za-z0-9_-]+)\|([^>|\n]*)>/g — group 1 the id, group 2 the name
function widgetToken(widget: Pick<Widget, "id" | "name">): string;
function widgetTokens(text: string): { id: string; name: string }[];
const widgetTokensToText: (text: string) => string;
```

- `widgetToken` builds the token. `|`, `>` and line breaks in the name become spaces; an empty name becomes "Widget".
- `widgetTokens` lists the widgets a text places, in order and once each.
- `widgetTokensToText` replaces tokens with `[Name widget]`, for previews and notification text.
- `WIDGET_TOKEN_RE` is global: reset `lastIndex` or use `matchAll`.

```ts
import { widgetToken, widgetTokensToText } from "@spacemix/sdk";

const text = `This week: ${widgetToken({ id: "w1", name: "Open tasks" })}`;
widgetTokensToText(text); // "This week: [Open tasks widget]"
```

**Stability:** stable. Tokens stay in message text for good. `WIDGET_TOKEN_RE` is versioned with the widget frame: the guard records it as written and refuses a change unless `WIDGET_FRAME_VERSION` moved. `widgetToken`, `widgetTokens` and `widgetTokensToText` follow the format; the guard checks their signatures like any other export.

## Layout helpers

`@spacemix/sdk` also exports the grid arithmetic Dashboards uses. On a dashboard, each item has a cell position and a size; the user puts it where they like and nothing moves up to fill gaps. When a move or resize makes items overlap, the ones in the way are pushed down, just far enough.

```ts
interface Box { id: string; x: number; y: number; w: number; h: number }

const overlaps: (a: Box, b: Box) => boolean;          // false for the same id
const bottomOf: (boxes: Box[]) => number;              // the first row below every box
function settle<T extends Box>(boxes: T[], fixed?: string[]): T[];
function place<T extends Box>(boxes: T[], moved: Box): T[];
function firstFree(boxes: Box[], w: number, h: number, cols: number): { x: number; y: number };
function fit<T extends Box>(boxes: T[], from: number, cols: number): T[];
```

- `Box` is any item with `id`, `x`, `y`, `w` and `h`. `overlaps` says whether two different boxes share a cell; `bottomOf` is the first row below every box.
- `settle` removes overlaps: boxes in `fixed` (ids) stay put, and every other box, top to bottom, moves down until it's clear of everything placed before it. Boxes that overlap nothing don't move. The result keeps the input order.
- `place` puts `moved` at its new position and size and settles the rest around it.
- `firstFree` is the top-most, then left-most, position where a `w`×`h` box fits without moving anything (`w` is capped at `cols`).
- `fit` shows a layout made for `from` columns on a narrower grid of `cols`: positions and widths scale down and the overlaps rounding makes are pushed apart. One column stacks everything in reading order. With `cols >= from` it returns the boxes unchanged.

```ts
import { place, GRID_COLS, fit } from "@spacemix/sdk";

const next = place(items, { id: "a", x: 0, y: 0, w: 6, h: 4 });
const onPhone = fit(next, GRID_COLS, 1);
```

**Stability:** experimental. These are pure functions with no host behind them, but they exist for Dashboards and may move.
