---
title: Panels
summary: >-
  Pages of your own HTML in the sidebar, with buttons and readouts that run your workflows and read
  your tables. Write one in the app, or build one with Preact and Vite and push it.
group: Workspace
order: 6
---

A panel is a page of your own HTML that sits in your sidebar, runs your workflows when you press its
buttons and reads the tables you let it read. For example, a "Lights" panel can show every lamp in
the house as a button, read their state through a workflow that talks to your Hue bridge over the
[Relay](/docs/relay), and toggle one with a second workflow when you tap it. You write a panel in
**Settings → Panels**, build it on your computer with Preact and Vite and push it, or ask an agent
to build and check one, and add it to the sidebar like any other page.

## How panels fit in your workspace

A panel draws whatever its HTML draws. Its data and actions come from
[workflows](/docs/workflows) it may run and [tables](/docs/collections) it may read, both named by
the panel's current version. It runs workflows as the person viewing it, the same as pressing
**Run** in the workflow editor, and reads what they return. A panel cannot reach the internet or
the rest of Verdalia on its own, so everything it changes goes through its workflows; the one
exception is a panel using [Iconify icons](#icons), which fetches them from Iconify. Workflows can
tell it when something changes, so it shows the change without asking again. It can open other
pages of your workspace, put an address of its own in the browser, copy text, show a count beside
its name in the sidebar, and keep a small value in the viewer's browser between visits.

## Ways to add a panel

- In the app, open **Settings → Panels** and select **New panel**.
- In the sidebar, choose **Edit Routes** from a page's menu, then the **Add panel** button at the top
  of the sidebar. Pick a panel to add, or **New panel** to start one.
- Ask an agent: "Build me a panel with a button for each of my lights" or "Make a panel that shows
  today's sales from my Stripe workflow, and add it to the sidebar." The agent creates the panel,
  then adds a page showing it with [Create Page](/docs/tools/create_page).
- From another AI app over [MCP](/docs/mcp), with the same panel tools agents use.

Once a panel exists, an agent pushes a build from your computer into it through a Relay; see
[Push a build](#push-a-build).

## Write a panel

To edit a panel, open it in **Settings → Panels**. Name and describe it, add the workflows it may
run under **Workflows it may run** and the tables it may read under **Tables it may read**. Each
list holds one grant per row, with a button to remove it, and an **Add** picker you search by name
or slug. **Vendor libraries** lists the libraries the panel may import, each with **Remove**, and
**Add vendor library** adds one. To put it in the sidebar, select **Add to navigation**.

The version's assets are listed above the editor: select one to edit it. **Save** writes the edited
assets as a new version and makes it the one everyone sees. The name and description save as you
leave them and belong to the panel. A change of workflows, tables or vendor libraries writes a new
version on its own, so switching to an earlier version brings back the lists that version had.

The editor changes the text of the assets a version holds. Adding or removing one needs an agent
("Add a chart.js to my Lights panel") or [push a build](#push-a-build).

## Files and versions

A panel is built from assets: one HTML file, `index.html` unless a push names another, and the
scripts, stylesheets and SVG images it uses. A file's name is at most 67 characters, extension
included, and ends in `.html`, `.js`, `.mjs`, `.css` or `.svg`, such as `app.js`. A vendor
library's own name, such as `verdalia-ui.js`, cannot be a file's name.

A version is one set of those assets, with an id of its own. Each asset in it has a name, an id, a
SHA-256 hash and a size, and an asset never changes: an edit stores the new text as another asset
and puts it in a new version, while the version before keeps the asset it listed. A file a later
version does not edit keeps the asset it had. Saving edited assets, a push and an agent's change to
files each write a new version from an earlier one. A version also names the workflows it may run,
the tables it may read and the vendor libraries it may use.

A panel points at one version, the current one, and that is what everyone who opens the panel sees.

### Reference an asset

The HTML names an asset with `asset:` and its name:

```html
<link rel="stylesheet" href="asset:app.css">
<script type="module" src="asset:app.js"></script>
<img src="asset:logo.svg" alt="">
```

Classic scripts run in the order the HTML gives them, and modules run in order after the page is
read. The editor lists each `asset:` name the version holds no asset for as "No file named …", and
the panel loads without it.

A module imports another of the panel's scripts as `asset:` and its name, and a vendor library by
its bare specifier, such as `preact` or `@verdalia/ui` (see
[Assets and vendor libraries](#assets-and-vendor-libraries)):

```js
import { formatTotal } from 'asset:format.js'
import { html, render } from '@verdalia/ui'
```

An import by a relative path, such as `./format.js`, does not load. A stylesheet's `url()` cannot
name another asset either.

Raster images, such as PNG and JPEG, and fonts are not assets: write them as `data:` URIs, in a
stylesheet, in an `<img src>`, or inlined by your bundler.

| What | At most |
|---|---|
| One asset | 1,048,576 bytes (1 MiB) |
| The HTML asset | 262,144 bytes |
| One version | 64 assets and 4 MiB together |
| Every asset every panel version lists | 50 MB |

Each asset reaches the panel at an address of its own, which works for whoever holds it until the
end of the following day. Keep passwords and keys out of a panel's assets.

### Switch versions and roll back

Under **Versions** in the editor, each version shows the start of its id, when it was made and its
size, and the one people see is marked **Current**. **Switch to this version** makes that version
the current one: that is how you roll back, and how you put live a version an agent or a push wrote
without switching. It is available while you have no unsaved edits.

Agents switch with [Switch panel version](/docs/tools/panel_switch) by the version's id.

An agent can also restore a version with [Update panel](/docs/tools/panel_update): "Restore my
Lights panel to yesterday's version." Restoring writes a new version with the same assets,
workflows, tables and vendor libraries as the one restored, and it becomes the current one unless
you ask the agent to stage it.

### Panel storage

**Settings → Panels → Storage** shows how much of the workspace's 50 MB the panel assets take, and
every panel's versions with the version's id, date and size.

- **Delete unused files** deletes the assets no version lists.
- Deleting a panel deletes its versions and the assets no other version lists.

A save or push that would take panel assets past 50 MB is refused with how much is in use. Switching
versions and changing a panel's settings always work.

## Run a workflow

A panel's script runs a workflow with `verdalia.api.executeWorkflow`:

```js
const run = await verdalia.api.executeWorkflow({ workflow: 'lights-q4m8x2-7hd2kp', input: {} })
console.log(run.output)
```

`workflow` is the workflow's slug or its id: the last part of the address while the workflow is
open. A slug carries a suffix of its own, so copy it; the workflow's name alone, such as `'lights'`,
resolves to no workflow. A panel runs only the workflows its current version lists, whichever
version is on screen, and any other call is refused with `not_allowed`.
The workflow's **Input** node receives `input`, and its **Set Workflow Output** node's value comes
back as `output`. The call waits for the workflow to finish, for up to five minutes. Pass
`wait: false` to start a run and return straight away with `{ status: 'started', jobId }`, and
`onProgress` to hear which step of the workflow is running. A panel can have four calls running at
once, counting table reads.

### Start a workflow at one of its Input nodes

One workflow can hold several Input nodes, one for each thing a panel asks of it: a "Lights"
workflow with one Input node that lists the lamps and another that toggles one. The panel names the
entry it needs with `startNode`, so one workflow per subject covers every button:

```js
await verdalia.api.executeWorkflow({ workflow: 'lights-q4m8x2-7hd2kp', startNode: 'input-2', input: { id: 'lamp-4' } })
```

`startNode` is the id of one of the workflow's Input nodes, such as `input` or `input-2`: the node's
id in the workflow, not its label. An agent reading the workflow with
[Get workflow](/docs/tools/get_workflow) sees every node's id. Without `startNode`, the workflow
needs exactly one Input node. Which node a call names is known only when the call is made, so a
panel is never checked for it when it is saved: a misspelled `startNode` shows only when that call
runs.

### When a call fails

A call that is refused, or whose run fails, throws an error with a `code`, a `message` the panel can
show, and the run's `jobId` when a run started:

| `code` | When |
|---|---|
| `not_allowed` | The workflow is not on the current version's list or names no workflow, the table is not one the panel may read, `verdalia.app.open` was given an address it does not open, or the panel called `open` or `setParams` while its page is not on screen. |
| `not_found` | The workflow on the panel's list, or the panel itself, no longer exists. |
| `no_input_node` | The workflow has no Input node, and no `startNode` was given. |
| `ambiguous_input_node` | The workflow has more than one Input node, and no `startNode` was given. |
| `invalid_input` | The call was malformed: `input` is not JSON or is over 256 KB, a table read's filter, order or limit cannot be run, the text to copy is over 64 KB, a badge count is outside 0 to 9999, a storage key is empty or over 256 characters, a stored value is not text or is over 64 KB, or `onEvent` was given a key that breaks the event key rule or a listener that is not a function. |
| `workflow_failed` | The run failed; `message` says why. |
| `timeout` | The run passed the workflow's time limit and was stopped. |
| `busy` | The panel already has four calls running. |
| `unauthorized` | The viewer's session has ended; signing in again fixes it. |
| `query_failed` | A table read failed; `message` says why. |
| `copy_failed` | The browser refused to put the text on the clipboard. |
| `badge_failed` | The sidebar count could not be saved. |
| `storage_failed` | The browser did not let the panel read or write its saved values. |
| `storage_full` | A save would pass the 1 MB a panel may keep in one browser. |

```js
try {
  await verdalia.api.executeWorkflow({ workflow: 'lights-q4m8x2-7hd2kp', startNode: 'input-2', input: { id } })
} catch (error) {
  status.textContent = error.code === 'busy' ? 'Still working…' : error.message
}
```

### When a workflow says no

A run that finishes has succeeded, even when the workflow decided against what it was asked: the
lamp is unreachable, or the order has already shipped. To tell the panel, the workflow ends with an
output of the shape `{ ok: false, error: { code, message } }`, and the panel checks for it. The
output reaches the panel exactly as the workflow set it.

A node that fails is not a "no". Leave its **Failure mode** at **Stop branch (default)**: the run
fails, and the call throws `workflow_failed` with a message saying why. To answer with a "no"
instead, set the node to **Route to error output**, wire its `error` output into a JavaScript step
that returns `{ ok: false, error: { code, message } }`, and wire that step into the same input of
Set Workflow Output as the success path.

```js
const { output } = await verdalia.api.executeWorkflow({ workflow: 'orders-b7n2c9-m3k8wq', startNode: 'ship', input: { order } })
if (output.ok === false) {
  status.textContent = output.error.message
  return
}
```

## Read a table

A panel reads rows of a table it may read with `verdalia.api.queryTable`. `table` is the table's id
or slug; the slug aliases the id, and either is accepted:

```js
const { rows, broken } = await verdalia.api.queryTable({
  table: 'lamps',
  filter: { room: 'den', on: true },
  order: [{ column: 'name', direction: 'asc' }],
  limit: 50,
})
for (const row of rows) addLamp(row.id, row.name)
```

`filter` keeps the rows whose columns equal the given values; `null` matches an empty cell. `order`
sorts by one column or several, each `asc` or `desc`. `limit` is 1 to 1,000, and 100 when left out.
Each row is `{ id, …columns }`. `broken` counts the rows left out because they no longer fit the
table's columns.

A table the panel may not read is refused with `not_allowed`, the same for any name. To let a
panel read a table, add it under **Tables it may read** in the panel's editor. An agent grants a
table or a workflow by its id or its slug, as `list_tables` and `list_workflows` give them, and
the version keeps its id; a reference that names no table or workflow is refused, naming it. The
grant is the whole table, so grant only tables whose every column the panel may show. A panel
changes a table through a workflow.

## Hear events from workflows

A workflow tells open panels that something changed with a
[Send User Event](/docs/nodes/send_user_event) step with **Send to listening clients** on. A panel
listens on a key with `verdalia.api.onEvent`, which returns a function that stops listening:

```js
const stop = verdalia.api.onEvent('notes.saved', (event) => {
  if (event.payload.document_id === shownId) reload()
})
```

`event` is `{ key, payload, sentAt }`, with `sentAt` an RFC 3339 time. Each call listens on one
exact key, so a panel calls `onEvent` once for each key it wants. Several listeners on one key are
called in the order they were added; one that throws does not stop the others, which still
run. Calling `stop` a second time does nothing. A panel can start listening before
`verdalia.ready`, and listening does not count toward the four calls a panel may have running.

A key is 1 to 64 characters, each a lowercase letter `a`–`z`, a digit `0`–`9`, `.`, `_` or `-`, the
first a letter or digit. A key that breaks the rule, or a listener that is not a function, throws
`invalid_input` at once, with a message naming the key and the rule.

A panel hears events only while it is open. Reloading it, switching to another version, or leaving
its page stops its listeners, and its script adds them again when it loads. Events sent while it was
closed, or while the viewer's connection to Verdalia was down, never arrive. Read the current state
when the panel loads, and treat an event as a cue to read again. If the workflow that sends is
disabled or deleted, the panel hears nothing.

Listening needs no grant: any panel in the workspace can listen on any key.

An event is a signal, not a delivery. Its payload says what happened in as few fields as it takes:
the id of the record that changed, or a small status. It never carries the data itself; whoever
hears the event reads what it needs from where that lives. A workflow that saves a note sends
`notes.saved` with `{ "document_id": "01M7BX3ZEQPHGZRWDXGXE2GF7Q" }`, not the note's text, and a
panel that hears `notes.saved` reads the note again through a workflow. The payload is capped at
1,024 characters, and an event sent to listening clients reaches every client listening on the
workspace, for every member of it.

## Know where the panel is and who is looking

A panel learns about its page once it connects. `verdalia.ready` resolves then, and
`verdalia.context` and `verdalia.app.params` are `null` until it does:

```js
await verdalia.ready
const { workspace, viewer, theme } = verdalia.context
// workspace: { id, slug, timezone }, viewer: { id, name, timezone }, theme: { mode: 'dark' | 'light' }
```

Use `verdalia.context.workspace.timezone` for anything the workspace schedules, such as deciding
which tasks are due today. It comes from **Settings** → **Preferences** → **Your day**.
Use `verdalia.context.viewer.timezone` to display times in the timezone of the viewer's device.

### Link into a panel

A panel's address can carry where the panel is: which lamp is open, which tab is showing. For a
panel shown at `/home/view/lights`, the address `/home/view/lights/lamp-4?tab=schedule` gives

```js
verdalia.app.params
// { resourceId: 'lamp-4', childResourceId: null, query: { tab: 'schedule' }, hash: '' }
```

`hash` comes without its `#`. A panel inside a space has `resourceId` only, and setting
`childResourceId` there is refused with `not_allowed`.

To change the address, call `verdalia.app.setParams` with the parts to change and how the change
goes into the browser's history. `push` adds an entry, so **Back** returns to where the panel was,
for example to close a dialog the panel opened; `replace` changes the address in place. Every call
names one of the two. A `query` key set to `null` is removed, and `childResourceId` needs a
`resourceId`. The call resolves with the new params once the address shows them.
`verdalia.app.onParamsChange` hears every change of address, from `setParams` and from **Back** and
**Forward**, and returns a function that stops listening. The panel keeps running through every
change, with its state as it was. Leaving the panel's page and coming back loads the panel afresh.

```js
await verdalia.app.setParams({ resourceId: 'lamp-4' }, { history: 'push' })
const stop = verdalia.app.onParamsChange((params) => showLamp(params.resourceId))
```

### Open other pages

`verdalia.app.open` takes a path in your workspace, such as `/home/library/shopping-list`, and opens
that page in place of the panel; or an `http` or `https` address, and opens it in a new tab. Any
other address, a path into another workspace, or a path that matches no page is refused with
`not_allowed`.

```js
await verdalia.app.open(`/${verdalia.context.workspace.slug}/library/shopping-list`)
```

## Copy text and show a count

`verdalia.app.copy(text)` puts up to 64 KB of text on the viewer's clipboard, and resolves once it
is there.

`verdalia.app.badge(count)` shows a whole number from 0 to 9999 beside the panel's name in the
sidebar, on every page that shows the panel; `0` clears it. The count is the panel's, so everyone in
the workspace sees the same number, and it stays until the panel sets another.

```js
await verdalia.app.copy(order.trackingNumber)
await verdalia.app.badge(orders.filter((o) => o.waiting).length)
```

Opening, params, copying, counts, and saving or reading a value do not count toward the four calls a
panel may have running.

## Use forms

A form's submit button, and Enter in one of its fields, run the form's `submit` listener, after the
browser's own checks such as `required` and `type="email"`. Handle the submission in the listener
and call a workflow from it:

```js
form.addEventListener('submit', async (event) => {
  event.preventDefault()
  await verdalia.api.executeWorkflow({ workflow: 'add-note-k3m9x1', input: { text: field.value } })
})
```

If the listener does not call `preventDefault()`, the panel stays as it is.

## Read the panel's console

What a panel writes with `console.debug`, `console.info`, `console.log`, `console.warn` and
`console.error` appears in your browser's developer console at the same level, marked with the panel
it came from. An error the panel's script did not catch, and a promise rejection nobody handled,
appear there too, as errors.

## Keep a value between visits

A panel keeps a small value in the viewer's browser with `verdalia.storage.set`, and reads it back
with `verdalia.storage.get` when it opens again:

```js
await verdalia.storage.set('last-room', 'den')
const lastRoom = await verdalia.storage.get('last-room') // 'den', or null
```

The value is a string, so keep an object by writing it as JSON and reading it back with
`JSON.parse`. A key with no saved value reads as `null`.

Values are saved under the panel's id and the panel's key, so two panels never see each other's
values. They belong to the browser, not the person: everyone who opens the panel in the same
browser shares them, and each browser keeps its own. A key is 1 to 256 characters, and a value is
up to 64 KB. A panel keeps at most 1 MB in one browser; a save that would pass that is refused with
`storage_full`. Clearing the browser's site data removes them. Never keep secrets,
credentials, tokens or keys, and nothing the panel's grant does not already expose.

## Use the app's colors

Every panel has Verdalia's colors, corner sizes and shadows as CSS variables on its page:
backgrounds, text, borders, buttons, state colors, chart series, the palette they come from, corner
sizes, and the shadows of cards, buttons and inputs.
[Panel colors](/docs/panel-colors) lists each one with its value.

```css
body {
  background: var(--verdalia-color-surface-primary, #16171a);
  color: var(--verdalia-color-text-primary, #bcbdc1);
}
button {
  background: var(--verdalia-color-element-primary, #37805f);
  color: var(--verdalia-color-on-element-primary, #0c0d0f);
  border-radius: var(--verdalia-radius-md, 10px);
}
```

Give each `var(--verdalia-…)` a fallback, as above, so the panel still reads well when its HTML is
opened outside Verdalia. To change a variable for one panel, set it in the panel's own `:root`:

```css
:root {
  --verdalia-color-element-primary: #c2410c;
}
```

## Match Verdalia's look

A panel can look however its HTML says. When there is no style to follow, the variables above make
it look like the rest of Verdalia, put together the way the app puts them together:

- The page is `surface-primary`. A section groups its content with a heading and a
  `border-subtle` rule under it, with the content on the page. Grouping never takes a fill or a
  shadow, so `surface-tertiary` and `surface-elevated` never mark a group, a stat or a chart area.
- A card holds one record, such as one order or one lamp: `surface-primary` fill, a
  `border-raised` border and `shadow-stoneprint-card`.
- A raised look means it can be pressed. A button is `surface-secondary` with a `border-raised`
  border and `shadow-stoneprint-button`, `shadow-stoneprint-button-hover` under the pointer and
  `shadow-stoneprint-button-active` while pressed. The main action is `element-primary` with
  `on-element-primary` text. An input, select or slider track is a well:
  `shadow-stoneprint-inset`.
- Values and titles are `text-primary`. A label is `text-secondary`, above what it labels, and a
  helper line is `text-tertiary`, below it. Labels are never uppercase, and never dimmed with
  opacity.
- A color says which one a thing is, or how it is going: `text-ok`, `text-warning`, `text-error`
  and `text-info`. A state is colored text, or an icon with text, without a pill behind it.
  Anything that says neither has no color.
- A chart sits on the page, and its series take `data-1` to `data-8` in that order. A chart of
  states colors each series by its state. Past eight series, use a table.
- A list of records is rows on the page with a `border-subtle` rule between them, never a card per
  row.

```html
<style>
  body { margin: 0; padding: 24px; font: 14px system-ui;
    background: var(--verdalia-color-surface-primary, #16171a);
    color: var(--verdalia-color-text-primary, #bcbdc1); }
  h2 { margin: 0 0 12px; padding-bottom: 8px; font-size: 15px; font-weight: 600;
    border-bottom: 1px solid var(--verdalia-color-border-subtle, rgb(255 255 255 / 0.06)); }
  .record { padding: 16px; border-radius: var(--verdalia-radius-md, 10px);
    background: var(--verdalia-color-surface-primary, #16171a);
    border: 1px solid var(--verdalia-color-border-raised, rgb(255 255 255 / 0.08));
    box-shadow: var(--verdalia-shadow-stoneprint-card, 0 2px 4px rgb(14 15 18 / 0.16), 0 8px 24px rgb(14 15 18 / 0.24)); }
  .label { color: var(--verdalia-color-text-secondary, #7d7e81); }
  .ok { color: var(--verdalia-color-text-ok, #527d49); }
  button { padding: 6px 12px; font: inherit; border-radius: var(--verdalia-radius-sm, 6px);
    background: var(--verdalia-color-surface-secondary, #212225);
    color: var(--verdalia-color-text-primary, #bcbdc1);
    border: 1px solid var(--verdalia-color-border-raised, rgb(255 255 255 / 0.08));
    box-shadow: var(--verdalia-shadow-stoneprint-button, 0 1px 3px rgb(14 15 18 / 0.18), 0 4px 12px rgb(14 15 18 / 0.18)); }
  button:hover { box-shadow: var(--verdalia-shadow-stoneprint-button-hover, 0 2px 4px rgb(14 15 18 / 0.2), 0 6px 16px rgb(14 15 18 / 0.24)); }
  button:active { box-shadow: var(--verdalia-shadow-stoneprint-button-active, inset 0 1px 3px rgb(14 15 18 / 0.28)); }
</style>
<section>
  <h2>Office lamp</h2>
  <div class="record">
    <div class="label">Brightness</div>
    <div>80%</div>
    <p class="ok">Reachable</p>
    <button>Turn off</button>
  </div>
</section>
```

[Panel colors](/docs/panel-colors) lists every variable with its value.

## Assets and vendor libraries

The assets of a version are its stylesheets, scripts and SVG images, and the HTML references one
with `asset:` and its name. Verdalia also ships vendor libraries: the panel kit, Preact, htm, the UI
kit, uPlot and Iconify icons. They come with the app at the build you are running. A vendor library
is never an asset of a version and takes no space in the workspace. It is always the library the
running Verdalia ships, so an update can change one without a new version of the panel. A version
lists the vendor libraries it may use by identifier, exactly as you give them.

| Identifier | What it is | Imported as |
|---|---|---|
| `verdalia-kit-1.js` | Panel kit | a classic script, `window.VerdaliaKit` |
| `verdalia-kit-1.css` | Panel kit styles | |
| `verdalia-ui.js` | Panel UI kit | `@verdalia/ui` |
| `verdalia-ui.css` | Panel UI kit styles | |
| `verdalia-preact.js` | Preact | `preact` |
| `verdalia-preact-hooks.js` | Preact hooks | `preact/hooks` |
| `verdalia-preact-jsx-runtime.js` | Preact JSX runtime | `preact/jsx-runtime` |
| `verdalia-htm.js` | htm | `htm` |
| `verdalia-uplot.js` | uPlot charts | `uplot` |
| `verdalia-uplot.css` | uPlot chart styles | |
| `verdalia-iconify.js` | Iconify icons | `iconify-icon` |

Add one under **Vendor libraries** in the editor. Agents name each identifier in the `vendors` list
they pass to [Update panel](/docs/tools/panel_update), [Create panel](/docs/tools/panel_create) and
[Push panel](/docs/tools/panel_push).

Some vendor libraries import others, and a list names those too:

| Vendor library | Needs |
|---|---|
| `verdalia-preact-hooks.js` | `verdalia-preact.js` |
| `verdalia-preact-jsx-runtime.js` | `verdalia-preact.js` |
| `verdalia-ui.js` | `verdalia-preact.js`, `verdalia-preact-hooks.js`, `verdalia-htm.js` |

A list without one of them is refused, naming the library and the one it needs, and nothing is
saved. A script never needs a stylesheet: add `verdalia-ui.css` for the UI kit's styles yourself.

### The panel kit

The panel kit is for a panel written without a framework. Add `verdalia-kit-1.css` and
`verdalia-kit-1.js` under **Vendor libraries**, then:

```html
<link rel="stylesheet" href="asset:verdalia-kit-1.css">
<script src="asset:verdalia-kit-1.js"></script>
```

The script gives the panel `window.VerdaliaKit` with:

- `modal({ title, content, actions })`: a dialog that keeps the keyboard inside it and closes with
  Escape;
- `confirm({ title, message, reasonLabel, requireReason })`: asks a question, optionally with a
  reason field, and resolves with `{ confirmed, reason }`;
- `toast(message, { kind, timeoutMs })`: a short message that goes away after four seconds;
- `relativeTime(date)`: "3 minutes ago" or "in 2 days";
- `sortableTable(table)`: sorts a table's rows by the column header the viewer clicks;
- `writeQueue({ debounceMs, write, onError })`: saves by key with `set(key, value)`, one save in
  flight per key, with only the last value of a burst sent, so two quick slider moves on one lamp
  land in order.

The kit's first lines describe every option; an agent reads them with
[Get panel file](/docs/tools/panel_file_get).

The kit's styles use the app's colors, including any the panel sets in its own `:root`.

## Build with Preact and the UI kit

`@verdalia/ui` is a small component library in Verdalia's look, with hooks that read your tables
and run your workflows. It hands a panel Preact's `h`, `render`, `Fragment` and hooks, and `html`,
which writes Preact elements without a build step.

Without a build, write the panel in a module script. Add `verdalia-ui.js`, `verdalia-ui.css`,
`verdalia-preact.js`, `verdalia-preact-hooks.js` and `verdalia-htm.js` under **Vendor libraries**:

```html
<link rel="stylesheet" href="asset:verdalia-ui.css">
<div id="app"></div>
<script type="module">
  import { html, render, Card, useTable } from '@verdalia/ui'
  function App() {
    const { rows, loading } = useTable({ table: 'tasks', limit: 20 }, { pollMs: 10000 })
    return html`<${Card} title="Tasks">${loading ? 'Loading' : rows.length}</${Card}>`
  }
  render(html`<${App} />`, document.getElementById('app'))
</script>
```

The components are `Card`, `Section`, `Stack`, `Row`, `Button` (primary, secondary or danger, with
a busy state), `List` and `ListItem`, `Table` (sorted by the header the viewer clicks), `Badge`,
`Field` with `Input`, `Select`, `Checkbox` and `Textarea`, `Spinner`, `Empty`, `ErrorNotice` and
`Modal`. `confirm`, `toast` and `relativeTime` work as in the panel kit.

The hooks keep a panel's state for it:

- `useWorkflow(workflow, { startNode, wait })` gives `{ run, running, result, error, progress }`.
  `run(input)` runs the workflow and resolves to its result, or to `undefined` when it failed and
  `error` says why.
- `useTable(query, { pollMs })` gives `{ rows, loading, error, refresh }` for a
  `verdalia.api.queryTable` query, read again every `pollMs` when given. The last rows stay on
  screen while a new read runs.
- `usePoll(load, ms)` gives `{ data, loading, error, refresh }` for any async function, in the same
  way.
- `useParams()` gives `{ params, setParams }`, and draws the panel again when its address changes.

### Charts

Add `verdalia-uplot.js` and `verdalia-uplot.css` under **Vendor libraries**, as well as the UI kit's
libraries for `seriesColor`, and draw with
[uPlot](https://github.com/leeoniya/uPlot). `seriesColor(i)` gives the app's color for series 1 to 8:

```js
import uPlot from 'uplot'
import { seriesColor } from '@verdalia/ui'

new uPlot(
  { width: 640, height: 240, series: [{}, { label: 'Sales', stroke: seriesColor(1) }] },
  [days, totals],
  document.getElementById('chart'),
)
```

## Icons

A panel shows icons from four Iconify sets: Phosphor (`ph`), Lucide (`lucide`), Simple Icons
(`simple-icons`) and Logos (`logos`). Browse them at
[icon-sets.iconify.design](https://icon-sets.iconify.design). An icon is named by its set's prefix
and its name in the set, such as `ph:lightbulb` or `logos:github-icon`.

Add `verdalia-iconify.js` under **Vendor libraries**, then load it and place each icon with
`<iconify-icon>`:

```html
<script type="module" src="asset:verdalia-iconify.js"></script>
<iconify-icon icon="ph:lightbulb" width="20"></iconify-icon>
<iconify-icon icon="logos:github-icon" width="20"></iconify-icon>
```

In a module script or a JSX panel, import it once and write the element:

```jsx
import 'iconify-icon'

export function HomeLink() {
  return <iconify-icon icon="ph:house" />
}
```

A Vite build keeps `iconify-icon` in Rollup's `external` list, as in
[Build with Vite](#build-with-vite).

The viewer's browser loads each icon from Iconify's service as the panel shows it, so Iconify sees
the viewer's address and which icons the panel shows. An icon shows only when the viewer's browser
can reach Iconify. An icon from any other set does not load, and its place stays empty.

## Build with Vite

A panel built on your computer is written in JSX and bundled by Vite into one module and one
stylesheet. Preact, the UI kit, uPlot and Iconify icons stay out of the bundle: the panel lists them
as vendor libraries, and its imports of `preact`, `@verdalia/ui`, `uplot` and `iconify-icon` load
those.

**1. Configure Vite.** Install `vite`, and `preact` as a dev dependency for its types. Then
`vite.config.ts`:

```ts
import { defineConfig } from 'vite'

export default defineConfig({
  esbuild: {
    // JSX compiles to imports of preact/jsx-runtime, which loads the vendor library.
    jsx: 'automatic',
    jsxImportSource: 'preact',
  },
  build: {
    outDir: 'dist',
    emptyOutDir: true,
    // Inline every image and font: a panel file is .html, .js, .mjs, .css or .svg text only.
    assetsInlineLimit: Number.MAX_SAFE_INTEGER,
    cssCodeSplit: false,
    modulePreload: false,
    rollupOptions: {
      // Vendor libraries; never bundled.
      external: ['preact', 'preact/hooks', 'preact/jsx-runtime', '@verdalia/ui', 'uplot', 'iconify-icon'],
      output: {
        format: 'es',
        inlineDynamicImports: true,
        entryFileNames: 'app.js',
        assetFileNames: 'app[extname]',
      },
    },
  },
})
```

For TypeScript, set `"jsx": "react-jsx"` and `"jsxImportSource": "preact"` in `tsconfig.json`.

**2. Link the kit's styles.** Vite's own `index.html` is the panel's HTML. Link the kit's stylesheet
there; Vite leaves the link as it is, with a note that it "doesn't exist at build time":

```html
<link rel="stylesheet" href="asset:verdalia-ui.css">
<div id="app"></div>
<script type="module" src="/src/main.tsx"></script>
```

**3. Add the kit's types.** Save this as `src/verdalia-ui.d.ts`:

```ts
declare module '@verdalia/ui' {
  import type {
    ComponentChildren,
    CSSProperties,
    HTMLAttributes,
    InputHTMLAttributes,
    SelectHTMLAttributes,
    TextareaHTMLAttributes,
    VNode,
  } from 'preact'

  export { h, render, Fragment } from 'preact'
  export * from 'preact/hooks'

  /** htm bound to Preact's h: html`<${Card} title="Tasks">…</${Card}>`. */
  export const html: (strings: TemplateStringsArray, ...values: unknown[]) => VNode | VNode[]

  /** A space between stacked or lined-up children. */
  export type Gap = 'sm' | 'md' | 'lg'
  /** What a Badge reports. */
  export type BadgeKind = 'neutral' | 'info' | 'ok' | 'warning' | 'error'
  /** How a button reads. */
  export type ButtonVariant = 'primary' | 'secondary' | 'danger'
  /** What a toast reports. */
  export type ToastKind = 'info' | 'ok' | 'warning' | 'error'

  /** Props every component passes through to the element it renders. */
  type Passed<E extends EventTarget> = Omit<HTMLAttributes<E>, 'title'> & { class?: string }

  /** One record: substrate fill, soft shadow and light border, with an optional title row. */
  export function Card(
    props: Passed<HTMLElement> & { title?: ComponentChildren; actions?: ComponentChildren; children?: ComponentChildren }
  ): VNode
  /** A titled region: heading, a rule beneath, content on the substrate. */
  export function Section(
    props: Passed<HTMLElement> & { title: ComponentChildren; actions?: ComponentChildren; children?: ComponentChildren }
  ): VNode
  /** Children in a column, `gap` apart (default 'md'). */
  export function Stack(props: Passed<HTMLDivElement> & { gap?: Gap; children?: ComponentChildren }): VNode
  /** Children in a row, `gap` apart; `align` (default 'center') and `justify` (default 'flex-start') are CSS values. */
  export function Row(
    props: Passed<HTMLDivElement> & {
      gap?: Gap
      align?: CSSProperties['alignItems']
      justify?: CSSProperties['justifyContent']
      children?: ComponentChildren
    }
  ): VNode
  /** A raised button; `busy` disables it and shows a spinner. `type` defaults to 'button'. */
  export function Button(
    props: Passed<HTMLButtonElement> & { variant?: ButtonVariant; busy?: boolean; children?: ComponentChildren }
  ): VNode
  /** Rows separated by rules. */
  export function List(props: Passed<HTMLUListElement> & { children?: ComponentChildren }): VNode
  /** One row of a List: its children are the title line, `meta` the line beneath; `onClick` makes it pressable. */
  export function ListItem(
    props: Omit<Passed<HTMLLIElement>, 'onClick'> & {
      meta?: ComponentChildren
      actions?: ComponentChildren
      onClick?: (event: MouseEvent) => void
      children?: ComponentChildren
    }
  ): VNode

  /** One column of a Table. Without `value`, the column reads `row[key]`; without `render`, it shows that value as text. */
  export interface TableColumn<Row> {
    key: string
    label: ComponentChildren
    value?: (row: Row) => unknown
    render?: (row: Row) => ComponentChildren
    /** false keeps the header from sorting. */
    sortable?: boolean
  }
  /**
   * Rows under sortable headers. A header click sorts by that column, ascending first and then
   * toggling: numbers as numbers, text naturally, equal values in their given order. `compare`
   * replaces that ascending comparison of two values as text; `column` is the column's index.
   * `rowKey` defaults to `row.id`, else the row's position.
   */
  export function Table<Row extends object>(
    props: Passed<HTMLTableElement> & {
      columns: TableColumn<Row>[]
      rows: Row[]
      rowKey?: (row: Row) => string | number
      compare?: (a: string, b: string, column: number) => number
    }
  ): VNode
  /** A state as ink: a dot and text in the state's colour (default 'neutral'). */
  export function Badge(props: Passed<HTMLSpanElement> & { kind?: BadgeKind; children?: ComponentChildren }): VNode
  /** A label above its control, with `hint` or `error` beneath; the control inside is described by it. */
  export function Field(
    props: Passed<HTMLLabelElement> & {
      label: ComponentChildren
      hint?: ComponentChildren
      error?: ComponentChildren
      children?: ComponentChildren
    }
  ): VNode
  /** A text input. */
  export function Input(props: InputHTMLAttributes<HTMLInputElement> & { class?: string }): VNode
  /** A select, from `options` or from option children. */
  export function Select(
    props: SelectHTMLAttributes<HTMLSelectElement> & {
      class?: string
      options?: { value: string; label: ComponentChildren }[]
      children?: ComponentChildren
    }
  ): VNode
  /** A multi-line text input. */
  export function Textarea(props: TextareaHTMLAttributes<HTMLTextAreaElement> & { class?: string }): VNode
  /** A checkbox with its label beside it. */
  export function Checkbox(
    props: InputHTMLAttributes<HTMLInputElement> & { class?: string; label: ComponentChildren }
  ): VNode
  /** A turning ring; `label` (default 'Loading') is what a screen reader hears, '' hides it from one. */
  export function Spinner(props: Passed<HTMLSpanElement> & { label?: string; size?: 'sm' | 'md' }): VNode
  /** What a place shows when it has nothing in it. */
  export function Empty(props: Passed<HTMLDivElement> & { title?: ComponentChildren; children?: ComponentChildren }): VNode
  /** An error's message, announced, with "Try again" when `onRetry` is given; renders nothing without an error. */
  export function ErrorNotice(
    props: Passed<HTMLDivElement> & { error: unknown; title?: ComponentChildren; onRetry?: () => void }
  ): VNode | null

  /** A button of a Modal's action row; without `onClick` it calls the Modal's `onClose`. */
  export interface ModalAction {
    label: ComponentChildren
    kind?: ButtonVariant
    disabled?: boolean
    onClick?: () => void
  }
  /**
   * A native <dialog> shown while `open`. Tab cycles inside it, Escape calls `onClose`, a click on
   * the backdrop does nothing. Focus goes to the [autofocus] control or the first control, and
   * returns where it was when it closes.
   */
  export function Modal(
    props: Omit<Passed<HTMLDialogElement>, 'open'> & {
      open: boolean
      title?: ComponentChildren
      onClose?: () => void
      actions?: ModalAction[]
      children?: ComponentChildren
    }
  ): VNode | null

  /** What confirm() asks. A reason field shows when `reasonLabel` is given or `requireReason` is true. */
  export interface ConfirmOptions {
    title?: string
    message?: string
    reasonLabel?: string
    requireReason?: boolean
    confirmLabel?: string
    cancelLabel?: string
    danger?: boolean
  }
  /** confirm()'s answer; `reason` is trimmed, and '' on a cancel or without a reason field. */
  export interface ConfirmResult {
    confirmed: boolean
    reason: string
  }
  /** Asks a yes-or-no question in a modal; Escape and Cancel answer `{ confirmed: false, reason: '' }`. */
  export function confirm(options: ConfirmOptions): Promise<ConfirmResult>
  /** Shows a short message in the panel's corner for `timeoutMs` (default 4000; 0 keeps it until dismissed). */
  export function toast(message: string, options?: { kind?: ToastKind; timeoutMs?: number }): { dismiss(): void }
  /** "3 minutes ago", "in 2 days": `date` relative to `now` (default the current time). */
  export function relativeTime(date: Date | number | string, now?: Date | number | string): string

  /** What a panel's `onProgress` hears about a call it is waiting for. */
  export type WorkflowProgress =
    | { type: 'started'; jobId: string }
    /** `nodeId` is the workflow's graph-local node id. */
    | { type: 'node'; nodeId: string; state: WorkflowNodeState }
    /** Sent every 15 seconds while nothing else arrives. */
    | { type: 'waiting'; elapsedMs: number }

  /** Where one node of a watched run has got to. */
  export type WorkflowNodeState = 'started' | 'completed' | 'failed' | 'skipped'

  /** How a panel's call settled successfully. */
  export type WorkflowResult =
    { status: 'succeeded'; jobId: string; output: unknown } | { status: 'started'; jobId: string }
  /** The state of useWorkflow. */
  export interface WorkflowCall {
    /** Runs the workflow with `input`; resolves to its result, or to undefined when it failed (`error` says why). */
    run(input?: unknown): Promise<WorkflowResult | undefined>
    running: boolean
    /** The latest result, kept while the next run is running. */
    result: WorkflowResult | undefined
    error: Error | null
    /** The running call's latest progress event. */
    progress: WorkflowProgress | null
  }
  /** Runs a workflow of the panel's on demand. */
  export function useWorkflow(workflow: string, options?: { startNode?: string; wait?: boolean }): WorkflowCall

  /** One table row: its id beside its columns. */
  export type TableRow = { id: string } & Record<string, unknown>
  /** What queryTable takes. */
  export interface TableQuery {
    table: string
    filter?: Record<string, string | number | boolean | null>
    order?: { column: string; direction: 'asc' | 'desc' }[]
    limit?: number
  }
  /** The state of useTable. */
  export interface TableRead {
    /** The latest rows; [] until the first answer, kept while a refresh or poll runs. */
    rows: TableRow[]
    /** True until the first answer for this query. */
    loading: boolean
    /** Why the latest read failed, null after one succeeds. */
    error: Error | null
    /** Reads now; resolves once the answer is shown. */
    refresh(): Promise<void>
  }
  /** Rows of a table the panel declares, read again every `pollMs` when given. */
  export function useTable(query: TableQuery, options?: { pollMs?: number }): TableRead

  /** The state of usePoll. */
  export interface PollRead<T> {
    /** The latest value; undefined until the first answer, kept while the loader runs again. */
    data: T | undefined
    loading: boolean
    error: unknown
    refresh(): Promise<void>
  }
  /** Any async loader, run now and again every `ms` when given. */
  export function usePoll<T>(load: () => T | Promise<T>, ms?: number): PollRead<T>

  /** The panel's params, as verdalia.app.params carries them. */
  export interface PanelParams {
    resourceId: string | null
    childResourceId: string | null
    query: Record<string, string>
    hash: string
  }
  /** A change to the params; an absent field is kept, null clears it. */
  export interface PanelParamsChange {
    resourceId?: string | null
    childResourceId?: string | null
    query?: Record<string, string | null>
    hash?: string
  }
  /** The panel's params, re-rendering when they change, and verdalia.app.setParams. */
  export function useParams(): {
    params: PanelParams | null
    setParams(change: PanelParamsChange, options?: { history?: 'push' | 'replace' }): Promise<PanelParams>
  }

  /** The app's colour for chart series `i`, 1 to 8, for uPlot; any other `i` throws a RangeError. */
  export function seriesColor(i: number): string
}
```

**4. Build and push.** `vite build` writes `index.html`, `app.js` and `app.css` to `dist`. Ask an
agent to push that directory with `verdalia-ui.js`, `verdalia-ui.css`, `verdalia-preact.js`,
`verdalia-preact-hooks.js`, `verdalia-preact-jsx-runtime.js` and `verdalia-htm.js` as its vendor
libraries, `verdalia-uplot.js` with `verdalia-uplot.css` if the panel draws charts, and
`verdalia-iconify.js` if it shows icons.

## Push a build

A push makes a new version of a panel from a directory of files on a computer running the
[Relay](/docs/relay), inside one of its mounts. An agent pushes it with
[Push panel](/docs/tools/panel_push): "Push lights/dist in my projects mount to my Lights panel,
with the UI kit and the libraries it needs as vendor libraries."

Every file under the directory is taken, named by its file name alone, so `dist/assets/app.js` is
`app.js`. Two files with one name, or a file that is not `.html`, `.js`, `.mjs`, `.css` or `.svg`,
such as an image or font the bundler did not inline, stops the push before anything is stored.
Only the files the workspace does not already hold are read from the Relay.

The HTML file, `index.html` unless you name another, is your bundler's as it emitted it: its
references to the other files, such as `src="/app.js"`, become `asset:` references. The new version
is made from the current version, or the one you name; it keeps that version's workflows, tables and
vendor libraries, and takes the push's files in place of its own. Name the vendor libraries the
build imports and they replace the base version's list; a name that is no vendor library is
refused.

The new version is what everyone sees at once, unless you ask the agent to stage it: it then waits
under **Versions** until someone switches to it. The agent learns the new version's id and the one
it was made from, so it can switch back. A refused push says why, such as a file over the size
limit, and stores nothing. A Relay too old for pushes refuses them;
[Running Verdalia Relay on Your Computer](/guides/relay-setup) covers updates.

## Agent tools

Agents find these tools in the **Workspace** tool group. They are on by default for other AI apps
over MCP.

- [List panels](/docs/tools/panel_list): lists the workspace's panels and the version each shows.
- [Get panel](/docs/tools/panel_get): reads a panel's settings, one version's assets, the workflows
  it may run, the tables it may read and the vendor libraries it may use.
- [Get panel file](/docs/tools/panel_file_get): reads one asset of a version, or a vendor library it
  lists.
- [Create panel](/docs/tools/panel_create): creates a panel, with its first version, which everyone
  sees at once. [Create Page](/docs/tools/create_page) adds a page showing it to the sidebar.
- [Update panel](/docs/tools/panel_update): writes a new version from asset changes, replaces the
  vendor libraries, changes the name, description, workflows or tables, and restores a version.
- [List panel versions](/docs/tools/panel_versions): lists a panel's versions by id, newest first.
- [Switch panel version](/docs/tools/panel_switch): makes a version the one everyone sees.
- [Push panel](/docs/tools/panel_push): makes a version from a build directory on a Relay.

An agent's change to a panel's assets goes live at once, and the agent learns the new version's id
and the one it was made from, so "put my Lights panel back the way it was" switches back. Ask the
agent to stage a change to keep it as a version you switch to yourself.

## Examples

### A light switch for every room

One "Lights" workflow has two Input nodes: one lists your lights with the Hue node over the Relay,
the other toggles one light by id. The panel draws a button per light, calls the toggle entry with
`startNode` when you press one, then refreshes.

### An order queue with a count in the sidebar

A workflow on a **Webhook Trigger** adds each order your shop sends to an Orders table. The panel
reads the waiting orders with `queryTable`, sets its sidebar count to how many there are, and ships
one through a "Ship order" workflow that answers `{ ok: false, error }` when the order has already
gone.

### A morning dashboard

A workflow gathers today's calendar blocks, open tasks and the weather into one object. The panel
shows them in the app's colors, refreshes every few minutes, and has a button that runs your "Plan my
day" workflow. Selecting a task opens it with `verdalia.app.open`.

### A note that refreshes itself

A "Save note" workflow updates a document with **Library** and ends with a Send User Event step:
key `notes.saved`, payload `{ "document_id": "{{ input.id }}" }`, **Send to listening clients**
on. The panel reads the note through a workflow when it loads, listens with
`verdalia.api.onEvent('notes.saved', …)`, and reads the note again when the event names the one it
shows.

### A sales chart built on your computer

A Vite project in a Relay mount draws a month of sales from a Sales table with `useTable` and
uPlot. After `vite build`, you ask an agent to push `dist` to the panel, and if the new chart is
wrong, to switch back to the version before.

## Troubleshooting

- A panel shows nothing, or stops updating: open your browser's developer console while the panel
  is open. What the panel logged, an error its script threw and did not catch, and a refused or
  failed call are written there, each line marked with the panel, in your browser only.
- "No file named …" in the editor: the version has no asset of that name. Add it with
  [Update panel](/docs/tools/panel_update), or push a build that holds the file.
- A panel open since the day before last fails to load a file it asks for now: reopen it.
- A save or push is refused because the workspace's panel assets are at 50 MB: delete older panels
  or unused files in **Settings → Panels → Storage**, then save or push again.
- "This panel no longer exists": the panel shown at this page was deleted. Remove the page from the
  sidebar, or add another panel.
- A panel cannot be deleted while a page in the sidebar shows it. Remove or hide that page first.

## Related

- [Workflows](/docs/workflows): what a panel runs.
- [Collections](/docs/collections): the tables a panel reads.
- [Pages](/docs/pages): boards, spaces, hidden pages and arranging your sidebar.
- [Relay](/docs/relay): reach devices and folders on your computer from a workflow, and push panel
  builds from it.
- [Panel colors](/docs/panel-colors): every color and corner-size variable a panel has, with its
  value.
- [Build a panel](/guides/building-panels): a pull-request panel built step by step.

