> ## Documentation Index
> Fetch the complete documentation index at: https://docs.blobhub.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Bridge Protocol

> How a custom widget talks to its playground: every call, event and refusal, and the host's rules.

A [custom widget](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widgets.md) reaches its playground only through the bridge, a
`MessagePort` the frame's bootstrap relays to the host. This page is version 1 of the bridge protocol as the host speaks
it: what a widget's entry exports, the messages on the port, every call, event and refusal, and the rules the host
applies to them. BlobHub builds its own widgets with [a kit](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widgets.md#the-kit);
everything here is what a widget needs without the kit, and [A widget without the kit](#a-widget-without-the-kit) is a
complete one in plain JavaScript.

## The entry

The definition's `entry` names an ES module that exports `mount(element, port)`. The frame's bootstrap page imports the
module and calls `mount` once: `element` is the frame's root element, and `port` is the widget's end of the bridge, a
`MessagePort` the bootstrap relays to the host. `mount` may return a promise, which the bootstrap waits for. A `mount`
that throws, or whose promise rejects, stops the widget: the playground shows `This widget failed to start: <message>`,
with the error's message clipped to 300 characters, in place of the frame. A frame whose bootstrap page does not answer
within 10 seconds of its creation, before the widget's code loads, shows `This widget did not start.`

A widget listens on the port with `addEventListener("message", …)` and then calls `port.start()`. Everything the widget
sends and receives travels on this one port. The bootstrap's own messages travel on the host's side and are never passed
either way: a widget neither receives one nor can post one. No bridge message carries `type`, so a widget may still
ignore every message with a `type`.

## Messages

Messages are plain objects posted on the port with `postMessage`, not JSON text. There are three kinds:

* **Request**, widget to host: `{id, method, params, session}`. `id` is a positive integer, starting at 1 and never
  reused on one port; `method` names a call; `params` is a plain object, and may be left out when a call takes none;
  `session` is optional, a field of the request beside `params` and not `ui.open`'s param of that name; the bullet
  **The session a call names** below says what it holds.
* **Reply**, host to widget: `{id, result}`, or `{id, error: {code, message, data}}` when the host refuses the call.
  `message` and `data` may be absent.
* **Push**, host to widget: `{event, data}`, an event the widget did not ask for by id.

```json Request theme={null}
{"id": 4, "method": "objects.write", "params": {"alias": "orders/review", "value": {"reviewed_by": "Ada Lovelace"}}}
```

```json Reply theme={null}
{"id": 4, "result": null}
```

```json Refusal theme={null}
{"id": 5, "error": {"code": "forbidden", "message": "ui.copy needs a permission the widget did not declare",
  "data": {"permission": ["clipboard", "write"]}}}
```

```json Push theme={null}
{"event": "object.changed", "data": {"alias": "orders"}}
```

* **Replies come in the order calls finish**, not the order they were sent: match each reply to its request by `id`. A
  reply is a refusal when its `error` is not `null`. A widget acts on its `code`, one of the [Refusals](#refusals); a
  refusal without a string `code` reads as `api_error`, and a code the widget does not know is still a refusal.
  `message` is for people.
* **Params are JSON values:** `null`, booleans, finite numbers, strings, and arrays and plain objects of them. A member
  set to `undefined` counts as absent, as JSON writes it. Binary, an `ArrayBuffer` or a typed array, is accepted only
  as `files.upload`'s `bytes`. Any other value a `MessagePort` can carry, such as a `Blob`, `File`, `Map`, `Set`,
  `Date`, a non-finite number, an `undefined` array element or binary anywhere else, is refused with `invalid_params`
  and `{param}` naming the top-level param that holds it, since the API would receive it altered.
* **The size cap.** A request is at most 4 MiB + 64 KiB (4,259,840 bytes). Its size is the UTF-8 byte length of its
  JSON, where each `ArrayBuffer` or typed array is written as `null` and adds its `byteLength`. A larger request is
  refused with `invalid_params` and `{bytes, limit}`, and so is a request JSON cannot encode, such as one holding a
  cycle or a `BigInt`. A file up to [`workflow.session_file_bytes`](https://docs.blobhub.io/general/limits#workflow) fits in one upload.
* **The schema.** The host checks every request: a plain object carrying `id` or `method` is a request, checked against
  the call's params as the tables below list them; any other message is ignored. The host evaluates nothing a widget
  sends.
* **Pinned.** Every call is pinned by the host to the playground's revision and its selected session at the moment of
  the call, and the host takes neither from params: the id `session.select` carries is the session to switch to, and a
  `debugger` link's must be the selected session. [When the session changes](#when-the-session-changes) says what
  happens when the viewer switches sessions while a call is under way.
* **The session a call names.** On a call marked [Session](#calls), `session` is the id of the session the widget last
  heard of, from `hello` or `session.changed`, or `null` when it heard of none; the kit's client sets it on every such
  call. Any value but the selected session's id, `null` included while one is selected, is refused with
  `session_changed` and nothing runs, so a write sent before the widget heard of a switch never lands in the session the
  viewer just picked. A call without `session` is pinned on arrival, and a `session` set to `undefined` counts as
  absent. On any call, a `session` that is neither a string nor `null` is refused with `invalid_params`; on a call not
  marked Session, the host checks nothing more of it.

## Handshake

A widget's first call is `hello`:

| Call | Params | Result | Permission | Session |
| - | - | - | - | - |
| `hello` | `{bridge}` | `{bridge, alias, ports, viewer, session, phase, theme, org}` | — | — |

`bridge` is the major version the widget speaks, `1`. The result:

* **`bridge`** is the version the host answers in. A widget built for bridge 1 refuses any other value and stops.
* **`alias`** is the widget definition's alias in the playground's revision.
* **`ports`** maps each port route the widget declares, and any other route the placed widget stores, to its value: the
  value set in the details pane, else the value the pane gives a new port, else `null`. A new port takes its declared
  `default`, a `null` one counting as none, else a value such as `0`, `""` or `false`, and a `message` port's value
  gets fresh `attributes`. A `component_alias` or `workflow_alias` port starts at `""` and a `credential` port at
  `null`, whatever their `default`, and a type the pane has no editor for reads `null`. Editing a port pushes
  [`ports.changed`](#watches-and-events) with the whole map; the frame is not reloaded.
* **`viewer`** is `{id, name, avatar, canWrite, anonymous}`: the person viewing the playground, `avatar` possibly
  `null`. `canWrite` is `true` when the viewer may edit the playground's revision and the selected session is open;
  while it is `false`, the host refuses every write, with `no_session` when no session is selected, `session_changed`
  when the write carries a `session` other than the selected session's id, `null` included, and `forbidden` otherwise.
  `anonymous` is `true` for a viewer who is not signed in.
* **`session`** is the selected session's summary, or `null` when none is selected. A summary is `{id, alias, status}`:
  `alias` is `null` for a session without one, and `status` is `null` for a session that has none, which is not open.
* **`phase`** is the revision's [phase](https://docs.blobhub.io/general/how-it-works.md#revisions-and-the-revision-lifecycle), `draft` or
  `commit`.
* **`org`** is the revision's organization, `{alias, name}`, and no other field.
* **`theme`** is `"light"` or `"dark"`, which the bootstrap has already set on `<html data-theme>`.
  [Libraries and Theme](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widget-libraries.md) covers the theme.

The host pushes nothing before it has answered `hello`, so a widget that sends it first misses no event. It is
answered within 10 seconds, or the widget gives up; see [Timeouts](#timeouts).

The playground loads a widget only when its definition's `bridge` is one the page speaks, today `1`; for any other it
shows `This widget was built for bridge <n>; this page speaks bridge 1.` instead of a frame. Within a major version,
additions never break a widget: a host answering bridge 1 also answers calls added to bridge 1 later, and its new events
and refusal codes reach widgets built before them unchanged. So a widget ignores an event it does not know, and treats a
code it does not know as a refusal.

## Calls

Each table lists a call's params, its result, and the permission it needs from the widget's
[permissions](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widgets.md#permissions), where a level above `read` implies `read`.
A call runs when the widget makes it, with nothing asked of the viewer: besides its params and its session, the host
checks what the widget declared, the viewer's own rights and the rate budgets below. Whoever installs the widget
confirms what it declares ([Trust at install](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widgets.md#trust-at-install)).
**Session** marks a call that needs a selected session, refused with `no_session` without one, a write included. A write
(`objects.write`, `objects.delete`, `threads.post`, `graph.mutate`, `files.upload` or `executions.start`) also needs a
viewer who can write in the selected session, or it answers `forbidden` with `{can_write: false, session_status}`, the
selected session's status when the host refused the write. A write naming another session is refused `session_changed`
first, so for a write that names a session, `session_status` is the status of the session it named. A `session_status`
of `open` means the viewer is a reader; any other value, `null` included, means the session closed under the call, and a
widget shows `The session has closed.` rather than the host's message. `—` means none or no, and a `?` marks an
optional param. A call that looks up something that does not exist answers `not_found`, with what it looked for as its
`data`. A write never answers `not_found`: the API's refusal of a write is `api_error`.

Each placed widget has two rate budgets. Its writes, a workflow start among them, share one budget of 50 calls in any 10
seconds with its copies, opens, saves and session moves (`ui.copy`, `ui.open`, `files.save`, `session.select` and
`session.follow`), and `ui.notify` has its own of 10 calls in any 60 seconds. A call over its budget is refused with
`rate_limited`. A call refused earlier in the [order](#refusals) spends nothing; one that passes spends one before it
runs, whatever it then answers.

The browser's own rules still apply: it may refuse a new tab, a clipboard write or a notification prompt that no click
preceded. That is a result, never a refusal: `ui.open` answers `{opened: false}`, `ui.copy` `{copied: false}` and
`ui.notify` `{shown: false}`.

### Session

| Call | Params | Result | Permission | Session |
| - | - | - | - | - |
| `session.get` | `{}` | the selected session's summary, or `null` | — | — |
| `sessions.list` | `{}` | `{sessions}`, a list of summaries | `sessions: read` | — |
| `session.select` | `{id}` | `null` | `sessions: select` | — |
| `session.follow` | `{}` | `null` | — | — |

* **`sessions.list`** lists the revision's sessions, metadata only.
* A session's summary is `{id, alias, status}`, as [`hello`](#handshake)'s `session` is. `session.get`,
  `sessions.list` and `session.changed` carry it.
* **`session.select`** asks the host to switch the playground to the session `id`. An id the revision does not hold is
  `not_found` with `{id}`. The selected session's own id changes nothing, and any other is selected; either way the
  reply is `null`, and the host pushes `session.changed` before it for another session.
* **`session.follow`** turns the playground's [Sync](https://docs.blobhub.io/general/playgrounds.md#staying-current) back on.

### Objects

| Call | Params | Result | Permission | Session |
| - | - | - | - | - |
| `objects.rows` | `{prefix?}` | `{rows: [{alias, type, updated_at, size}]}` | `objects: read` | yes |
| `objects.read` | `{alias, fresh?}` | `{alias, type, value}` | `objects: read` | yes |
| `objects.watch` | `{alias}` | `null` | `objects: read` | — |
| `objects.unwatch` | `{alias}` | `null` | `objects: read` | — |
| `objects.watch_rows` | `{prefix}` | `null` | `objects: read` | — |
| `objects.unwatch_rows` | `{prefix}` | `null` | `objects: read` | — |
| `objects.write` | `{alias, value}` | `null` | `objects: write` | yes |
| `objects.delete` | `{alias}` | `null` | `objects: write` | yes |

* **`objects.rows`** lists the selected session's objects whose alias starts with `prefix`, or all of them. Each row is
  `{alias, type, updated_at, size}`: `type` is the object's type once the playground has read it, written it or heard
  it written, and `null` until then, as for an object it has only listed; `updated_at` is the time of the object's last
  write, or `null`; and `size` is its size in bytes from the session's object list, or `null`. A value is read with
  `objects.read`, which also answers the type a row lacks.
* **`objects.read`** answers the object's `type` and `value`, and `not_found` with `{alias}` when the session holds no
  such object. `fresh: true` asks for a read from the API rather than a copy the page already holds.
* **`objects.write`** stores `value`, a JSON object, as the object's whole value, creating the object when the alias
  is new, as [Upload Session Object](https://docs.blobhub.io/blob-types/workflow/operations/upload-session-object.md) does. Since a write
  replaces the whole value, a widget that changes part of a value reads the object `fresh` first. The API's refusals,
  such as an alias outside the grammar or a value over the size limit, answer `api_error`.
* **`objects.delete`** deletes the object and answers `null`, also when the session holds no such object; either way a
  widget watching the alias hears `object.changed`. The API's refusals answer `api_error`, as `objects.write`'s do.
* **`objects.watch`** and **`objects.unwatch`**: see [Watches and events](#watches-and-events).
* **`objects.watch_rows`** watches the rows whose alias starts with `prefix`, and **`objects.unwatch_rows`** stops;
  `prefix` is required, and `""` is every row. A row watch is held as an alias watch is, across session switches: see
  [Watches and events](#watches-and-events).

### Threads

| Call | Params | Result | Permission | Session |
| - | - | - | - | - |
| `threads.list` | `{alias, page?}` | `{items, cursor}` | `threads: read` | yes |
| `threads.get` | `{alias, item_id}` | the item | `threads: read` | yes |
| `threads.watch` | `{alias}` | `null` | `threads: read` | — |
| `threads.unwatch` | `{alias}` | `null` | `threads: read` | — |
| `threads.post` | `{alias, content, parent_id?, metadata?}` | the item posted | `threads: post` | yes |

* **`threads.list`** pages back from the newest item. `page` is `{cursor, limit}`, both optional. Without a `cursor` it
  answers the newest page; each page's `items` are oldest first, and its `cursor`, passed back unchanged, answers the
  page before it. `cursor` is `null` once the thread's start is reached.
* Items are the [thread items](https://docs.blobhub.io/blob-types/workflow/session-objects/thread/introduction.md#thread-items) the API stores.
  `threads.list` on a thread the session does not hold is `not_found` with `{alias}`, and `threads.get` is `not_found`
  with `{alias, item_id}` when the thread or the item is missing. A read of an alias that holds another kind of object
  is `not_found` too, and a post onto one answers the API's refusal, `api_error`.
* **`threads.post`** posts as the viewer: `content` is a list of content blocks, and `parent_id` and `metadata` are
  optional, as [Post Session Thread Item](https://docs.blobhub.io/blob-types/workflow/operations/post-session-thread-item.md) takes them. The
  reply is the item posted, with its `id`. A post to an alias that holds nothing creates the thread, as the operation
  does.

### Graphs

A session's [graphs](https://docs.blobhub.io/blob-types/workflow/session-objects/graph/introduction.md) are among its objects, so
`objects.rows` lists them. Each `graph.*` call is one of the graph's operations on the selected session, and answers
that operation's result unchanged:

| Call | Params | Result | Permission | Session |
| - | - | - | - | - |
| `graph.list` | `{alias, options?}` | a page of elements, from [List Session Graph Elements](https://docs.blobhub.io/blob-types/workflow/operations/list-session-graph-elements.md) | `graph: read` | yes |
| `graph.get` | `{alias, ids}` | the elements, from [Get Session Graph Elements](https://docs.blobhub.io/blob-types/workflow/operations/get-session-graph-elements.md) | `graph: read` | yes |
| `graph.neighbors` | `{alias, from, options?}` | the neighbors, from [List Session Graph Neighbors](https://docs.blobhub.io/blob-types/workflow/operations/list-session-graph-neighbors.md) | `graph: read` | yes |
| `graph.query` | `{alias, query}` | the result of [Query Session Graph](https://docs.blobhub.io/blob-types/workflow/operations/query-session-graph.md) | `graph: read` | yes |
| `graph.watch` | `{alias}` | `null` | `graph: read` | — |
| `graph.unwatch` | `{alias}` | `null` | `graph: read` | — |
| `graph.mutate` | `{alias, operations}` | the result of [Apply Session Graph Mutations](https://docs.blobhub.io/blob-types/workflow/operations/apply-session-graph-mutations.md) | `graph: write` | yes |

* **`ids`** is one element id or a list of them; **`from`** the vertex ids whose neighbors to fetch; **`query`** the
  traversal query; **`operations`** the list of mutations; **`options`** the operation's optional fields.
* A graph the session does not hold is `not_found` with `{alias}` on a read, and so is an alias that holds another kind
  of object. On `graph.mutate` either is the API's refusal, `api_error`, as any write's refusal is.

### Files

| Call | Params | Result | Permission | Session |
| - | - | - | - | - |
| `files.read` | `{alias}` | an `ArrayBuffer` | `files: read` | yes |
| `files.save` | `{alias}` | `null` | `files: read` | yes |
| `files.upload` | `{alias, name, type, bytes}` | the result of [Upload Session File](https://docs.blobhub.io/blob-types/workflow/operations/upload-session-file.md) | `files: write` | yes |

* **`files.read`** answers the file's bytes, the one result that is not JSON.
* **`files.save`** has the host save the file to the viewer's downloads under its stored name, and answers `null` once
  the host has handed the file to the browser. A browser may still block or ask about repeated downloads, which the
  host cannot see. It writes nothing to the session, so it needs only `files: read`, and a viewer who cannot write may
  save.
* **`files.upload`** creates or replaces a [file object](https://docs.blobhub.io/blob-types/workflow/session-objects/file/introduction.md):
  `name` is the file's name, `type` its MIME type, which must be on the content-type allow-list, and `bytes` an
  `ArrayBuffer` or typed array, the one binary param.
* A file the session does not hold is `not_found` with `{alias}` on `files.read` and `files.save`. `files.upload`
  creates it, and answers the API's refusal, such as an alias that holds an object other than a file, with `api_error`.

### Executions

| Call | Params | Result | Permission | Session |
| - | - | - | - | - |
| `executions.start` | `{workflow, input_data?}` | the result of [Create Execution](https://docs.blobhub.io/blob-types/workflow/operations/create-execution.md) | `executions` | yes |

* **`workflow`** is a [workflow reference](https://docs.blobhub.io/blob-types/workflow/workflows/workflow-reference.md) object, and
  **`input_data`** the run's input as Create Execution takes it. The workflow runs in the selected session, as the
  viewer. The run's writes do not carry the page's [client tag](https://docs.blobhub.io/blob-types/workflow/workflows/session-events.md#client),
  so they reach the page through the playground's event stream, as [any other writer's change](#watches-and-events)
  does, and may bring a watching widget no push until [Sync](https://docs.blobhub.io/general/playgrounds.md#staying-current) is on again.
* **The permission.** The reference must equal, key for key, one the widget lists under `executions`; otherwise the
  call is `forbidden` with `{permission: ["executions"]}`. Only an entry that is a well-formed workflow reference, in
  one of its three shapes, counts: BlobHub neither starts nor shows any other entry of a stored document. A workflow
  that a `workflow_alias` port of the widget names starts only if the list names it too. Such a port holds its workflow
  in the [path form](https://docs.blobhub.io/blob-types/workflow/workflows/workflow-reference.md#the-path-form), as `ports` shows it, and the
  widget passes the object that path names: `approve-order` is `{definition: "approve-order"}`,
  `<blob id>/<revision>/<definition>` is `{blob, revision, definition}`, and `org/blob/revision/definition` is
  `{org, blob, revision, definition}`.

### People

| Call | Params | Result | Permission | Session |
| - | - | - | - | - |
| `people.get` | `{user_id}` | `{id, name, avatar}` | — | — |

* **`people.get`** answers a person's display name and avatar and nothing more of them, as a thread already shows
  them. A person the platform does not know is `not_found` with `{user_id}`.

### Interface

| Call | Params | Result | Permission | Session |
| - | - | - | - | - |
| `ui.header` | `{alias?, actions}` | `null` | — | — |
| `ui.copy` | `{text}` | `{copied}` | `clipboard: write` | — |
| `ui.open` | `{url}`, or `{route, …}` | `{opened}` | `links` for a `{url}`; none for a route | — |
| `ui.notify` | `{title, body?}` | `{shown}` | `notifications: show` | — |

* **`ui.header`** sets what the host draws in the widget's header beside its name: `alias`, the text of its alias chip,
  a string of at most 128 characters; and `actions`, required, at most 4, each `{id, label, icon}`. `id` and `label` are
  strings of at most 64 characters, and `icon` is optional and, when given, a string of at most 64 characters naming a
  react-icons icon, resolved as [`widget.yaml`](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widgets#widget-yaml)'s `icon`
  is. An `alias` or `icon` of `null` is refused. A call whose `actions` is missing, or is not an array of at most 4
  actions within these bounds, is refused whole, not only the action at fault, with `invalid_params` and
  `{param: "actions"}`; one whose `alias` is out of bounds is refused with `{param: "alias"}`. Each call replaces the
  chip and the actions: an `alias` left out or `""` draws no chip, and `actions: []` clears the actions.

  The host draws each action as an icon button, as the built-in widgets draw theirs, with `label` as its
  tooltip and accessible name and never as text, so a label never widens the header. A missing `icon`, or
  one the page cannot find, draws `LuMousePointerClick`. When the viewer presses an action, with a click,
  Enter or Space, the host only pushes `ui.action` with its `id`; Space also presses it on a [free-form
  layout](https://docs.blobhub.io/blob-types/workflow/playgrounds/definition-format.md#free-form-layout)'s canvas. The header starts
  empty each time the widget loads and empties when the host stops the widget and shows a status in its
  place, so a widget calls `ui.header` each time it starts.
* **`ui.copy`** copies `text` to the viewer's clipboard and answers `{copied}`, `true` only when the browser copied it.
* **`ui.notify`** shows a desktop notification titled `<widget name>: <title>`, with `body` as its text, under
  blobhub.io's own notification permission, and answers `{shown}`, `true` only when the browser showed it. Where the
  permission is granted it shows; where it is denied the call answers `{shown: false}` without asking. While it is
  undecided, blobhub.io asks the browser at most once per page load, one ask shared by every widget on the page, and
  only from a call made while the page holds the browser's transient activation, which a click or key press on the
  page gives for a short time. Such a call asks, or waits for the ask already open; a call without activation answers
  `{shown: false}` and leaves the ask for a later call that has it. So a widget makes its first `ui.notify` from the
  viewer's click. A call after an ask that left the permission undecided, and any failure to ask or show, answers
  `{shown: false}`, never `api_error`.

**`ui.open`** opens a new tab, at one of three targets:

| Target | Opens |
| - | - |
| `{url}` | an absolute `https` address on a host the widget's `links` allows |
| `{route: "debugger", session, execution?}` | the [debugger](https://docs.blobhub.io/general/debugger.md) on the selected session, at one execution when `execution` is given |
| `{route: "profile", user}` | a person's profile |

`url` is an absolute `https` address with no user or password that reads the same with and without a base, and each
of `session`, `execution` and `user` is an id, a string matching `^[A-Za-z0-9_-]{1,128}$`. Any other key, route or value
is `invalid_params`: another scheme, `http` included; a URL carrying a user or password, since
`https://docs.example.com@evil.example/` reads as one host and opens another; and a URL such as `https:a.com/x`, whose
host alone is `a.com` but which a browser would resolve against the page as a path on blobhub.io. The host opens exactly
the URL it checked, as it parsed it, never the widget's string: `https://a.com\@b.com` opens `https://a.com/@b.com`.
A `debugger` link to a session other than the selected one is `forbidden` with `{param: "session"}`, and a `{url}` on a
host the widget's `links` does not name is `forbidden` with `{permission: ["links"]}`. A named route needs no
permission, since the host builds the link. The host never opens a `javascript:`, `data:` or `blob:` address, and never
builds a link from a path the widget chose.

`links` is either `["*"]` alone, which lets a widget open any `https` host, or a list of hosts, declared as
[Permissions](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widgets.md#permissions) says. An entry matches the URL's
host when the two are equal, case aside; `*.example.com` matches every host under `example.com`, at any depth, as
`a.example.com` and `a.b.example.com`, and never `example.com` itself. Matching reads the host alone, so any port
passes. An entry is never an IP address, so a URL whose host is one opens only under `["*"]`.

## Watches and events

`objects.watch`, `threads.watch` and `graph.watch` register the widget's interest in an alias, and the matching
`unwatch` drops it. A watch needs no session, and the alias need not exist yet. The interest survives session
switches, so a widget watches an alias once, not once per session. It is one mark per alias, not a count: one
`unwatch` drops it, however many `watch` calls came before.

The host pushes `object.changed`, `thread.item_posted` and `graph.changed` for a watched alias only while a session is
selected, only for that session, and only to a widget whose permissions let it read that kind. An event names what
changed and carries no value: a widget re-reads.

A data write a widget makes, with `objects.write`, `objects.delete`, `files.upload`, `threads.post` or `graph.mutate`,
carries the page's [client tag](https://docs.blobhub.io/blob-types/workflow/workflows/session-events.md#client), so the stream does not echo it
back to the page. The page announces the write itself, once, as it does a built-in widget's, so a widget watching that
alias hears its own write once, like anyone else's:

* `object.changed` with `{alias}` after `objects.write`, `objects.delete` or `files.upload`: a file is a session object,
  watched with `objects.watch`.
* `thread.item_posted` with `{alias, item_id}` after `threads.post`.
* `graph.changed` with `{alias}` after `graph.mutate`.

The push can arrive before the call's reply. Only a post can be told apart: `threads.post`'s reply is the item posted,
whose `id` the push's `item_id` matches. An object or graph push names only the alias, so a widget re-reads either way.

Any other writer's change reaches the page through the playground's own [event
stream](https://docs.blobhub.io/blob-types/workflow/workflows/session-events.md), filtered for the widget, not a second connection, so it brings a
push only while the playground's [Sync](https://docs.blobhub.io/general/playgrounds.md#staying-current) is on. With Sync off, the host still
pushes for a data write any custom widget on the page makes, its own or another's; any other change may bring none
until Sync is on again and the playground catches up, whether the viewer turns Sync on or the widget does with
[`session.follow`](#session).

`objects.watch_rows` watches every row whose alias starts with its prefix, and is held as an alias watch is: it needs no
session, survives session switches and is one mark per prefix. The host pushes `object.rows_changed` with that prefix
when an object under it is written or deleted in the selected session, the widget's own `objects.write`,
`objects.delete` and `files.upload` included. It pushes at once, then at most once per 250 ms for each prefix, so a
burst of changes ends in one last push. The event carries no rows, so a widget calls [`objects.rows`](#objects) again.
It may come when no object changed. After a session switch, once the new session's objects are listed, a push comes for
each prefix that has rows there. With Sync off, the host still pushes for an object any custom widget on the page
writes or deletes; any other change may bring none until Sync is on again and the playground catches up, or until the
playground next lists the session's objects.

| Event | Data | When |
| - | - | - |
| `ports.changed` | `{ports}`, the whole map, as [`hello`](#handshake) carries it | the placed widget's port values changed, as when the details pane edits one |
| `session.changed` | `{session}`, a summary or `null` | another session was selected, or none is; or the selected session's summary changed, a close included |
| `viewer.changed` | `{viewer}` | the viewer changed, or whether they can write did, as a close does |
| `theme.changed` | `{theme}` | the page switched between `light` and `dark` |
| `object.changed` | `{alias}` | a watched object changed |
| `object.rows_changed` | `{prefix}` | the rows under a watched prefix changed |
| `thread.item_posted` | `{alias, item_id}` | an item was posted to a watched thread |
| `graph.changed` | `{alias}` | a watched graph changed |
| `stream.gap` | `{}` | events were missed, so anything read may be stale; pushed only while a session is selected |
| `ui.action` | `{id}` | the viewer pressed one of the header's actions set by `ui.header` |

On `session.changed` and on `stream.gap`, a widget re-reads everything it shows. On `theme.changed`, it sets
`<html data-theme>` itself; the bootstrap set it only before the entry loaded.

## Refusals

A refused call answers `{id, error: {code, message, data}}`. The host checks a call in this order and answers the
first check that fails, so a widget can predict the code:

1. `unknown_method`.
2. `invalid_params`: the `id`, the size cap, `params` being an object, `session` a string or `null`, then each param.
3. `forbidden`: an undeclared permission, an `executions.start` workflow the widget's `executions` does not list, a
   `{url}` on a host its `links` does not list, or a `debugger` link to another session.
4. `no_session`, a write included.
5. `session_changed`, when a Session call carries a `session` other than the selected session's id, `null` included.
6. `forbidden`: a write by a viewer who cannot write in the selected session.
7. `rate_limited`.
8. `session_changed`, when the selected session changed before the call runs.
9. The call itself: `not_found` or `api_error`.
10. `session_changed`, when a read ran but its session changed before the reply.

| Code | Data | Meaning |
| - | - | - |
| `unknown_method` | `{method}` | the host speaks no such call |
| `invalid_params` | `{param}`, naming the param at fault; or `{bytes, limit}` | the request fails the host's checks, or is over the size cap; a request whose `id` is not a positive integer is answered with `id: null` and `{param: "id"}`, one whose `params` is not an object with `{param: "params"}`, and one whose `session` is neither a string nor `null` with `{param: "session"}`; a `ui.header` whose `actions` is missing or not an array of at most 4 actions within bounds is refused whole with `{param: "actions"}`, and one whose `alias` is out of bounds, `null` included, with `{param: "alias"}` |
| `forbidden` | `{permission}`, always a list: the `[key, level]` the call needs, or `["executions"]` or `["links"]`, the two keys whose value is a list; `{can_write: false, session_status}`, the selected session's status when the host refused the write (the session the write named, if it named one), `null` for a session with no status; or `{param: "session"}` | the widget did not declare the permission, the workflow or the link's host; the viewer cannot write in the selected session (`canWrite` is `false`), as a reader when `session_status` is `open`, and otherwise because the session closed under the call, which a widget shows as `The session has closed.` rather than the host's message; or a `debugger` link names another session |
| `no_session` | — | the call needs a selected session, a write included, and none is selected |
| `rate_limited` | — | the call is over one of the widget's two rate budgets |
| `session_changed` | — | nothing ran, because a Session call carried a `session` other than the selected session's id, `null` included, or the selected session changed first; or a read ran and its data was withheld. Never a call whose effect took place |
| `not_found` | `{alias}`, `{alias, item_id}`, `{id}` or `{user_id}` | what a call looks up does not exist, or a graph or thread read finds another kind of object at its alias; a write never answers it, since the API's refusal of a write is `api_error` |
| `api_error` | `{status, error?, reasons?}`, when the API answered | the API refused the call: `status` is its HTTP status, `error` its error code when the response names one, as `{status: 409, error: "session_not_open"}` for a closed session, and `reasons` the response's list when it has one, as a graph mutation conflict's. A field of the wrong type is dropped alone, and `data` is absent with none left. A host failure, and a reply the host withholds, carry no `data` |
| `unsupported_bridge` | — | raised by a client, never sent by the host: `hello` answered another major version |
| `timeout` | — | raised by a client, never sent by the host: `hello` had no answer within 10 seconds |
| `closed` | — | raised by a client, never sent by the host: the client closed the bridge with the call pending |

## When the session changes

* With no session selected, the widget's frame stays loaded and live, whereas a built-in widget shows a status asking
  for one. A call marked Session answers `no_session`, a write included. The other calls work, and watches stay
  registered. A widget draws its own empty state, and one that declares `sessions: select` may offer its own picker:
  [`sessions.list`](#session), which needs no session, lists the revision's sessions, and `session.select` selects one.
* The host pins a Session call to the session selected when it arrives. A call whose `session` is not that session's
  id, as when the widget sent it before it heard of a switch, answers `session_changed` on arrival, and nothing runs.
  The host checks again just before the call runs. If the selection changed, nothing runs and the call answers
  `session_changed`. For this second check the host compares session ids, so a session selected again by then counts as
  unchanged.
* A read that ran, whose session changed before its reply, answers `session_changed` with its data withheld, so a
  widget never shows one session's data under another.
* A call with an effect, a write or `files.save`, that ran answers with what it did, its real result or its real
  error, whatever is selected by then. So a widget does not repeat a write that answered, and a `session_changed`
  from a write means nothing was written.
* `session.changed` is pushed when another session or none is selected, and again for the same session whenever its
  summary changes, a close included. A close that ends the viewer's write rights pushes `session.changed`, then
  `viewer.changed` with `canWrite: false`. A widget re-reads on `session.changed` and on `stream.gap`; a re-read of a
  thread starts again from its newest page.

## Timeouts

`hello` is answered within 10 seconds; a widget with no answer by then gives up. No other call times out.

## A widget without the kit

One complete widget in plain JavaScript, with no library and no build step. It shows the session object its `orders`
port names, follows it as it changes, and at a click records a review beside it, in the object `<alias>/review`. Its
`widget.yaml`:

```yaml theme={null}
label: Order Review
description: The orders in the selected session, and a button that records a review of them.
entry: index.js
ports:
  - {category: data_input, route: orders, value: {type: component_alias}}
  - {category: data_input, route: width, value: {type: integer, default: 700, range: {from: 100, to: 2000, step: 50}}}
  - {category: data_input, route: height, value: {type: integer, default: 500, range: {from: 100, to: 2000, step: 50}}}
permissions:
  objects: write
```

The build directory holds one file, `index.js`:

```javascript theme={null}
// Order Review: shows the session object the `orders` port names, and records a review of it at a click.
export function mount(element, port) {
  const pending = new Map();
  const handlers = new Map();
  let lastId = 0;
  let viewer = null;
  let alias = null;
  let reads = 0;
  let shown = false;

  const status = document.createElement("p");
  const view = document.createElement("pre");
  const button = document.createElement("button");
  button.textContent = "Mark reviewed";
  button.disabled = true;
  element.replaceChildren(status, view, button);

  const show = (text) => {
    status.textContent = text;
  };
  const enable = () => {
    button.disabled = !shown || !viewer || !viewer.canWrite;
  };

  function call(method, params = {}) {
    lastId += 1;
    const id = lastId;
    return new Promise((resolve, reject) => {
      pending.set(id, { resolve, reject });
      port.postMessage({ id, method, params });
    });
  }

  function refusal(error) {
    const failure = new Error((error && (error.message || error.code)) || "refused");
    failure.code = error && typeof error.code === "string" ? error.code : "api_error";
    failure.data = error && error.data;
    return failure;
  }

  port.addEventListener("message", (event) => {
    const message = event.data;
    // No bridge message carries a `type`; skip any that does.
    if (message === null || typeof message !== "object" || "type" in message) {
      return;
    }
    if ("id" in message) {
      const request = pending.get(message.id);
      if (request) {
        pending.delete(message.id);
        if (message.error == null) {
          request.resolve(message.result);
        } else {
          request.reject(refusal(message.error));
        }
      }
    } else if (typeof message.event === "string" && handlers.has(message.event)) {
      handlers.get(message.event)(message.data);
    }
  });
  port.start();

  async function refresh() {
    reads += 1;
    const read = reads;
    shown = false;
    enable();
    if (!alias) {
      view.textContent = "";
      show("Set the orders port to the component whose output this widget shows.");
      return;
    }
    try {
      const object = await call("objects.read", { alias });
      if (read === reads) {
        view.textContent = JSON.stringify(object.value, null, 2);
        shown = true;
        show("");
        enable();
      }
    } catch (error) {
      // A read refused with session_changed is followed by the session.changed push, which reads again.
      if (read !== reads || error.code === "session_changed") {
        return;
      }
      view.textContent = "";
      if (error.code === "no_session") {
        show("Select a session to see its orders.");
      } else if (error.code === "not_found") {
        show(`This session has no object ${alias}.`);
      } else {
        show(error.message);
      }
    }
  }

  function follow(ports) {
    const previous = alias;
    alias = ports && typeof ports.orders === "string" && ports.orders ? ports.orders : null;
    if (alias !== previous) {
      if (previous) {
        call("objects.unwatch", { alias: previous }).catch((error) => show(error.message));
      }
      if (alias) {
        call("objects.watch", { alias }).catch((error) => show(error.message));
      }
    }
    refresh();
  }

  button.addEventListener("click", async () => {
    button.disabled = true;
    const value = { reviewed_by: viewer.name, reviewed_at: new Date().toISOString() };
    try {
      await call("objects.write", { alias: `${alias}/review`, value });
      show(`Marked reviewed by ${viewer.name}.`);
    } catch (error) {
      if (error.code === "session_changed") {
        show("The session changed first, so nothing was written.");
      } else if (error.code === "forbidden" && error.data && error.data.can_write === false
          && error.data.session_status !== "open") {
        show("The session has closed.");
      } else {
        show(error.message);
      }
    }
    enable();
  });

  handlers.set("ports.changed", (data) => follow(data.ports));
  handlers.set("session.changed", () => refresh());
  handlers.set("stream.gap", () => refresh());
  handlers.set("object.changed", (data) => {
    if (data.alias === alias) {
      refresh();
    }
  });
  handlers.set("viewer.changed", (data) => {
    viewer = data.viewer;
    enable();
  });
  handlers.set("theme.changed", (data) => {
    document.documentElement.dataset.theme = data.theme;
  });

  async function start() {
    show("Connecting…");
    const timer = setTimeout(() => show("The playground did not answer."), 10000);
    const hello = await call("hello", { bridge: 1 });
    clearTimeout(timer);
    if (hello.bridge !== 1) {
      show(`This widget speaks bridge 1, and the playground answered bridge ${hello.bridge}.`);
      return;
    }
    document.documentElement.dataset.theme = hello.theme;
    viewer = hello.viewer;
    follow(hello.ports);
  }

  start().catch((error) => show(error.message));
}
```

* **The port.** `mount` listens before it sends anything, ignores every message with a `type`, settles a pending call
  by its reply's `id`, and hands each push to the handler for its `event`; an event without one is ignored. Its
  requests carry no `session`, so the host pins each call to the session selected when it arrives.
* **The handshake.** `hello` goes first, with `{bridge: 1}`; the widget stops on any other `bridge`, and says so if
  no answer comes within 10 seconds.
* **The reads.** It watches the alias its `orders` port names, once, and reads it on `hello`, on `object.changed` for
  that alias, on `session.changed`, on `stream.gap` and when the port changes. A counter drops a reply that a newer
  read has overtaken.
* **The write.** `objects.write` is called from the click handler. Its `session_changed` says nothing was written, and
  its `forbidden`, when `session_status` is anything but `open`, says the session has closed. It writes
  `<alias>/review`, an alias it does not watch, so no push follows its write, and it says itself that the write landed.
  The button stays disabled until `hello` has answered and the object is shown, and while the viewer cannot write.
* **The theme.** It sets `<html data-theme>` from `hello`'s `theme`, which is current even if the page switched while
  the entry loaded, and again on each `theme.changed`, for a stylesheet to key its light and dark colors on.

## See also

* [Custom Widgets](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widgets.md): `widget.yaml`, the definition, permissions and
  trust at install, and deploying.
* [Libraries and Theme](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widget-libraries.md): the library catalog, building one
  module, and BlobHub's light and dark look.
* [Security Model](https://docs.blobhub.io/blob-types/workflow/playgrounds/custom-widget-security.md): the frame and its origin, the rules the
  platform enforces, and the risks that remain.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.