Remotehost Docs

App protocol

The contract every app builds to, in any language - the declaration's rules and seed, the declared views, and the backend and client WebAssembly worlds

An app is a manifest, a backend declaration, its views and up to two WebAssembly components built against wit/app.wit (package remotehost:app@1.0.0, in @remotehost/apps). An app whose rules and views say all it does needs no component at all. The TypeScript SDK and the Rust crate both build to it; any language with component tooling can. Building an app is the guide; this page is the contract.

Versions

app.wit 1.0.0 is pre-release until the first published app: no component outside this repository is built against it yet. Until the first published app, any record change rebuilds every guest; from then on, 1.0.0 is frozen and changes go in a new major folder, which hosts keep beside every old one. A declaration states its version as "protocol": 1.

The declaration

The backend declaration, plus three things:

KeyMeaning
protocol1
validators"backend.wasm", when the app has backend code; absent otherwise
seedrecords made when a workspace enables the backend
types.<type>.rulesthe rule settings below

Rules

The server keeps these for a type, with no code, before any validator runs:

RuleShapeWhat the server does
number{ field, per?, text, format, on_move?, history? }Sets field to the next value of a counter, one counter per value of per (or one for the type), and text to format with {number}, {<field>} or {<ref>.<field>} filled in. On an update the number stays, unless per changed and on_move is "renumber" (the default is "keep"); then history, a text field, collects the earlier texts as a JSON array.
author[field, ...]Sets each to the writing person when the record is made. A write that changes one is refused.
writer[field, ...]Sets each to the writing person on every write.
immutable[field, ...]A write that changes one after creation is refused.
reserved{ field, in }Refuses a value of field that a live record holds in in ("<type>.<field>"), unless the record already had it.
principaltrueThe type's records are the backend's people, with a person's id as the record id. The server makes one the first time a person writes; no one else may write one.

Seed

"seed": [
  { "type": "list", "name": "inbox", "fields": { "title": "Inbox" } },
  { "type": "item", "fields": { "list_id": "$inbox", "text": "Try ticking this off" } }
]

Records are made in order. A field value "$<name>" is the id of the earlier seed record with that name.

Records cross as JSON

Records, action inputs and results cross the contract as JSON text (type json = string), because their shape comes from each app's schema. Views are JSON in the package (views.json), read by the host and never sent across the contract: no guest draws anything.

Time and randomness

A guest imports no WASI, so its clock and entropy are the host's, through the contract:

  • client-host.now and transaction.now return milliseconds since the Unix epoch. The backend's is the time the write's transaction started: the same for every validator and after-write in one write.
  • client-host.random(len) and transaction.random(len) return len bytes from the host's secure generator, different in every instance.
  • The TypeScript SDK puts Date.now(), new Date(), Date() and Math.random on them when the component starts; the Rust crate has now_ms and random_bytes.

Ids

The host makes ids, so they are UUIDv7s whichever guest asked:

  • client-host.write takes record ops (put_record, update_record, delete_record, as backends define them). A put_record may leave out id, and the host gives it a UUIDv7. It returns a JSON array of the ops' record ids, in op order.
  • transaction-write.put without an id gets a UUIDv7 too, and returns the record as stored, with its id.

The backend world

world backend {
  import transaction;        // now, random, get, find, count: inside the write's transaction
  import transaction-write;  // put, update, delete
  export validate: func(kind: string, old: option<json>, next: option<json>, by: actor) -> result<_, refusal>;
  export after-write: func(kind: string, old: option<json>, next: option<json>, by: actor) -> result<_, refusal>;
}
  • Both run inside the write's transaction, after the rules. old is absent on create, next on delete.
  • validate only reads. after-write runs once validators pass and may write: its writes are planned, validated and followed by their own after-write as a client's are. A client write's after-write writes at level 1, theirs at level 2, and so on; levels 1 to 4 are allowed.
  • find(q, r, among) and count(q, among) match the records whose fields equal q's where-equal and, for each among, have one of its values (a JSON array). A field with no value reads as null: a null in the where-equal or among the values matches it, as a client host's find matches it.
  • Each call is a new instance, with no state from another call, and has limits:
LimitValue
Time50 ms of guest time; time spent waiting on the host does not count
Memory64 MiB, summed over the component's instances
Table elements100,000, summed over the component's instances
Reads (get, find, count)10 a call
Writes (put, update, delete)100 an after-write call
Records one find returns100
Matches one find seesThe first 1,000, in its order: total counts at most 1,000, which means that many or more, and a range past them returns none
Matches one count countsAll of them, in one read. A rule over a set of any size, such as a project's issues, costs the same few reads
random64 KiB a call
One op, all its calls1 s of wall time for every validate and after-write call one client op sets off, at every level, with the host's planning and writing of their nested writes; the time a nested write's locking reads wait does not count, up to 1 s of such waits in all, but a cascade delete's walk of the records that point at it counts, waits included

A lock wait is bounded by the database's lock_timeout instead, and an op's lock waits by 1 s in all: past either, the op is retried, never refused. So is a write to a backend whose validators this org's version of it has not installed yet, as during a rollout: the op is retried, and a client is told to retry if they are still not installed after a few tries.

now is the transaction's start (Postgres's now()), the same for every call in one write.

What a guest is told

A host import that fails returns a refusal to the guest, with one of these codes. Where the last column says so, the write ends refused that way whatever the guest does with the refusal:

SituationCode the guest getsHow the write ends
A write (put, update, delete) from validateread_onlyinvalid validator_failed
A write from after-write past level 4too_deepinvalid validator_failed
A nested write a validator refusedthat validator's own codeinvalid validator_refused, current.code its code
A nested write whose validator or after-write traps or runs out of memoryvalidator_failedinvalid validator_failed
A nested write whose validator or after-write times outvalidator_timeoutinvalid validator_timeout
A nested write refused by planning or the rulesthe refusal's reason (unknown_field, unknown_type, ...), else its code (invalid, forbidden, ...)that refusal
A nested write to the principal typeforbiddenforbidden, field type
An 11th read in one callread_limitinvalid validator_read_limit
A 101st write in one after-write callwrite_limitinvalid validator_failed
A write once the op is past its 1 svalidator_timeoutinvalid validator_timeout
get, find or count of an undeclared typeunknown_typeas the guest answers
find or count naming a field that is neither declared nor id (a find's order may also name created_at and updated_at)unknown_fieldas the guest answers
find or count on another backendforbiddenas the guest answers
A record, or where-equal, that is not a JSON objectinvalidas the guest answers
A store error (a lock timeout, a deadlock, the connection)unavailableretried or failed, never a final refusal
The write is overhost_gone

random past 64 KiB answers no bytes, and the write ends invalid validator_failed.

How the write is refused

A write a backend call refused carries the protocol's refusal (sync protocol), code invalid, with one of these reasons, for validate and after-write alike:

ReasonWhenfield, current
validator_refusedthe call returned a refusalthe refusal's field; current.code is its code
validator_timeoutthe call ran past 50 ms of guest time, or the op's calls past 1 s in allnone
validator_read_limitthe call read more than 10 timescurrent.code is read_limit
validator_failedthe call trapped (an exception the app did not turn into a refusal, memory or tables past their limits), asked for too many random bytes, wrote from validate, wrote more than 100 times, or wrote past level 4for the last three, current.code is the code the guest was told: read_only, write_limit or too_deep; otherwise none

The rule settings refuse with the protocol's own codes before any call: invalid with the field (with a reason such as unknown_field or restricted where one applies), not_found, precondition_failed with current, and forbidden for a principal type.

Views

Every screen of an app is data, not code: its lists, boards and detail pages are declared in views.json, beside backend.json in the package, and the host draws them with its own engine over the local replica. No app code draws a screen. The host reads the file without running any of the app's code, so an app with no client.wasm at all still draws its screens, and an app's list costs what the host's own lists cost.

{ "version": 1, "views": [ { "id": "cards", "kind": "table", ... } ] }

version is 1, under the same promise as app.wit. The file is generated, as backend.json is: by defineView in TypeScript (remotehost-app build), or by the Rust crate's remotehost_app::view types (the app writes it, and a test holds it current).

A view is one of two kinds:

KindWhat it draws
tableRows of a type, as a list or a board
detailOne record by id ($scope.id): a header and sections of fields

One view, abridged from Issues' own:

{ "id": "issues", "kind": "table", "title": "Issues", "noun": "issues",
  "backend": "issues", "type": "issue",
  "joins": { "status": {"field": "state_id", "type": "state"},
             "labels": {"through": {"type": "issue_label", "from": "issue_id", "to": "label_id"}, "type": "label"},
             "comments": {"many": {"type": "comment", "on": "issue_id"}} },
  "where": {"eq": ["archived", 0]},
  "scope": { "project": {"eq": ["project_id", "$scope.project"]} },
  "tabs": [ {"id": "all", "label": "All issues"},
            {"id": "active", "label": "Active", "where": {"in": ["status.type", ["unstarted", "started"]]}} ],
  "search": { "label": "title", "keywords": ["labels.name"], "identifiers": ["identifier"], "body": ["description", "comments.body"] },
  "facets": [ {"id": "priority", "label": "Priority", "path": "priority",
               "values": {"enum": [{"value": 1, "label": "Urgent"}, {"value": 2, "label": "High"}]}} ],
  "groupings": [ {"id": "status", "label": "Status", "by": "status", "key": "state",
                  "values": {"all": true, "order": [{"path": "position"}], "title": "name", "merge": "name"},
                  "folded": {"in": ["type", ["completed", "canceled"]]}, "gives": {"state_id": "id"}} ],
  "orderings": [ {"id": "priority", "label": "Priority", "sort": [{"path": "priority", "rank": [1, 2, 3, 4, 0]}]} ],
  "layouts": ["list", "board"],
  "columns": [ {"key": "status", "title": "Status", "style": "status",
                "value": {"object": {"type": "status.type", "color": "status.color", "name": "status.name"}}, "action": "set-status"},
               {"key": "title", "title": "Title", "value": "title", "grow": true} ],
  "address": {"format": "atlas://issue/{identifier}"},
  "actions": [ {"id": "set-status", "label": "Set status",
                "set": {"field": "state_id", "pick": {"title": "Set status", "values": {"type": "state", "label": "name"}}}},
               {"id": "set-label", "label": "Labels", "app": true} ],
  "keys": [ {"keys": "f", "action": "filter", "label": "Filter", "lead": true}, {"keys": "s", "action": "set-status"} ] }

The view

Every key but id, backend and type may be left out.

KeyMeaning
idThe view's name, which a route and a view node open it by
kindtable (the default) or detail
titleThe page's title
nounWhat a row is, plural: the header's count reads 12 issues
backend, typeThe backend and the type it lists, or the type of the record a detail shows
joinsOther records a path reads through, by name (below)
whereWhat every row is, always
scopeOne clause per route parameter, applied only when the route gives it: a project's Issues tab is the same view with {"project": id}
tabsEach {id, label, where?}; the first is the default
searchThe header's search field and what it finds (below)
facetsThe Filter menu (below)
groupings, orderingsThe Display menu's groupings and orderings, the first of each the default
optionsThe Display menu's toggles and choices (below)
defaults{group?, order?, layout?}: defaults other than the first
layoutsThe layouts the person may switch between: list, board
columnsThe row's template (below); the board's card draws from the same columns, by style
addressEach row's atlas:// address. A row opens there with no call into the app, and the page it opens steps through the rows as shown (J, K)
detailA detail view's header and sections
actionsDeclared actions (below)
keysEach {keys, action, label?, lead?}: s, or a chord g m, running a declared action or one of the host's. One with a label is a header button, before the search field when it is lead
group_actionsEach {icon, label, action} at a group header's end, on a list's group row and a board column alike: add (a plus) or more (an ellipsis)
emptyWhat the page says in place of its rows, by why: not_granted (the backend is not served to this workspace), nothing (nothing matches)

Expressions

An expression is JSON, never code in a string:

  • a string is a path into the row (title, or status.type through the join status), or a binding when it starts with $;
  • a number, a boolean or null is itself;
  • an object of one key is an operator.
OperatorMeaning
{"lit": v}v as it is, a string too
eq, ne, lt, le, gt, geTwo operands: {"eq": ["archived", 0]}
{"in": [a, [values]]}a is one of them; a list-valued a when any of its values is
{"and": [...]}, {"or": [...]}, {"not": e}Logic
{"is_null": a}a is null or absent
{"has": a}a is present at all: an absent binding is not
{"coalesce": [...]}The first that is not null
{"first": [...]}The first that is not null and not empty text
{"if": c, "then": a, "else": b}One or the other
{"ago": "7d"}$now less a span of m, h or d
{"object": {k: e}, "of": p}An object; null when the path p is
{"each": p, "object": {k: e}}One object per value of the list p
{"format": "atlas://issue/{identifier}"}Text with paths filled in

The bindings are $now, $viewer (the person signed in), $tab, $scope.<name>, $target.<path> (the row an action is for), $picked.<path> (what a pick chose), $group.<name> (the group an action runs on) and $value (a group's value).

An empty text reads as null, and so does a missing field. An absent binding makes a comparison false and a value absent: {"eq": ["assignee_id", "$viewer"]} holds of no row when nobody is signed in. Text compares as a time only where a sort says time, and against {"ago": ...} or $now: both sides are read as RFC 3339, and a side that does not read makes the comparison false.

Joins and paths

A join names other records a path reads through:

JoinShapeGives
A ref{"field": "state_id", "type": "state"}The record the row's field names, or null
A link{"through": {"type": "issue_label", "from": "issue_id", "to": "label_id"}, "type": "label", "order": [...]}The records a link type ties to the row, in order (by id when none is given)
Many{"many": {"type": "comment", "on": "issue_id"}}The records whose on names the row, in their natural order

A path's first part is a field of the row or a join's name; its next parts are fields of the joined record. A path through a link or many join is a list (labels.name): in holds when any of its values is among those given, and eq when any equals. id is every record's own id.

Groups, facets and options

A grouping is {id, label, key, by?, title?, values?, none?, within?, icon?, folded?, gives?, progress?}. Each group's key is {key}:{value}, which folds and hidden groups are kept by.

  • No by: one group of every row, keyed key and titled title.
  • by a path with values.enum: one group per value, in order.
  • by a ref or a link join: the groups are records of the joined type. With values.all, every record values.where keeps is a group, as well as every one a row names; without it, only those a row names. Groups are in values.order, titled by values.title (default name). With values.merge (a field), records of one value are one group, as statuses of one name are. A row of a link join is in every group of its linked records.
  • none: {title, key, always?, icon?, gives?}, the group of rows with no value, last. Without always, it is there only when some row is in it.
  • within: {by, order?, title?, join, include?, gives?} nests one grouping in another, as milestones in their projects (values.parent names a value's parent). When the rows have several parents, a group's title is the parent's, join (›), and its own.
  • icon ({style, value}), folded and gives are read of the group's record ($value for an enum). gives are the fields a group gives what is made in it, by its +: {"state_id": "id"}.
  • progress: {on, where?, skip?, done} counts done over a group's whole set, the rows of the type whose on names the group's record, whatever the view shows. It draws as a bar.

A facet is {id, label, path, values, choice?, none?}: the Filter menu's "is any of". values is {"enum": [{value, label}]} or records of a type, {"type", "where"?, "order"?, "label", "value"?}, whose records of one value merge into one choice. choice is the choice's label, with {label} filled in (or {labels}, merged values' joined by , ). none is a first choice for no value: No assignee.

An ordering is {id, label, sort}, each sort key {path, desc?, rank?, fold?, time?}: ranked values first in rank order, then every other value ascending, nulls first; desc reverses the key; fold compares text lowercased; time reads text as RFC 3339. The sort is stable.

An option is a toggle (default true or false, with on and off clauses, or empty_groups to show empty groups) or a choice of several (choices, each {id, label, where?}, default a choice's id).

Search is {label, keywords?, identifiers?, body?}, each a path or paths. A row matches when Atlas's own ranking finds the text in it, the same ranking as its command palette, so a search finds what Atlas finds.

Columns and cell styles

A column is {key, title, style, value, action?, grow?, width?}. Its value is an expression, read when its row draws (never for rows out of view); action runs a declared action on a click, on this row; width is in pixels. A value that isn't the shape its style names draws as text.

StyleValue
plain, muted, property, personText
dateAn ISO date or time, drawn as a date
relative-dateAn ISO date or time, drawn short: Nov 6
status{"type": "started", "color": "#f2c94c", "name": "In Progress"}, the type one of triage, backlog, unstarted, started, completed, canceled
priority0 none, 1 urgent, 2 high, 3 medium, 4 low
avatar{"id": "u-1", "name": "Ann Lee"}, or null for nobody
labels[{"name": "Bug", "color": "#eb5757"}]
icon-text{"icon": "project", "color": "#5e6ad2", "text": "Launch"}, the icon one of the host's

Atlas draws every style. The console draws no views: at most it shows an app's records in a record browser.

Detail views

A detail view's detail is {title, eyebrow?, body?, sections}: the record's title, words above it (REM-12), its long text, drawn as markdown, and sections of fields. A section is {title, fields}, a field {key, label, style, value, action?}, its action a set that changes it.

The state

A view's state is JSON the host keeps in the route, so Back and a link return to it. Every key may be left out:

{ "tab": "active", "search": "text", "filter": {"status": ["started"], "assignee": [null, "u01"]},
  "group": "status", "order": "priority", "layout": "board",
  "options": {"completed": "past_week", "subissues": false},
  "hidden": ["state:Todo"], "selected": "<row id>", "scope": {"project": "p01"} }

filter maps a facet's id to the values ticked, null for its none. hidden holds hidden groups' keys. selected is the cursor's row, which the host keeps as the cursor moves. scope holds the route's parameters. Absent, a tab, grouping, ordering and layout are the defaults, and an option its default. The host keeps keys it does not know as they are.

The host's own actions

Every view has these, and no app declares them: they change the view's state and call no app.

  • filter and display: the Filter and Display menus, from the facets and from the layouts, groupings, orderings and options. The Filter button reads Filter · 2 when two values are ticked.
  • layout: list and board swap (alt-cmd-b).
  • tab and search: the tab, and the search text (tab and shift-tab step the tabs).
  • group-menu: a group's Select all in column and Hide column.

Folds, the cursor, selection and scroll are the host's too.

Declared actions

An action is {id, label?} and one of:

  • set: {field, pick, also?} sets field of each target row to a value picked. pick is {title, values, none?}, values an enum or records of a type, whose where may read $target.*. A choice is ticked when every target has it. Each target gets one update_record, with also's fields beside the field, which may read $picked and $now: "completed_at": {"if": {"eq": ["$picked.type", "completed"]}, "then": "$now", "else": null}.
  • open: {address, query?} opens an address, with ?name=value for each query pair whose value is present, each value percent-encoded. A group's + reads $group.gives.<field>.
  • put: {fields} makes a record of the view's type.
  • app: true: runs the client's start-action with this id. Its input is {"ids": [...], "id": "<cursor's row>", "group": "<key>", "gives": {...}, "state": {...}, "view": "<view>"}: the targets' ids and the group's gives, never their records. Issues' label pick, one label per label group, is one.

The writes of set and put are the host's, made with the person's rights, as the app's own writes are.

Local first

Every read on a view's path is the local replica: the workspace's records in Atlas, with its unsent writes on top. A write is applied locally first and shows at once, then goes to the Atlas server's outbox, which RemoteHost Sync takes when it can. Nothing a view draws waits on a server: with RemoteHost Sync out of reach every view still draws, a write still shows, and it syncs when the connection comes back.

An app with no code

An app needs WebAssembly only for what a declaration cannot say: actions with app: true, and the backend's validators and after-write. An app with none of those is app.toml, a schema and its views: remotehost-app build writes backend.json and views.json and no component, and Atlas draws its lists, boards and detail pages and makes its declared writes.

Writing views

In TypeScript, with defineView, typed by the app's schema (its paths are checked against it where TypeScript can), and defineViews for the file:

import { defineView, defineViews } from "@remotehost/apps";
import schema from "./schema.ts";

export const cards = defineView(schema, {
  id: "cards",
  title: "Cards",
  noun: "cards",
  type: "card",
  joins: { owner: { field: "owner_id", type: "user" } },
  groupings: [{ id: "stage", label: "Stage", by: "stage", key: "stage",
                values: { enum: [{ value: "todo", label: "To do" }, { value: "done", label: "Done" }] } }],
  columns: [{ key: "title", title: "Title", value: "title", grow: true }],
  actions: [{ id: "set-owner", label: "Owner", set: { field: "owner_id",
              pick: { title: "Owner", values: { type: "user", label: "name" }, none: "No owner" } } }],
});

export default defineViews(schema, [cards]);

The app's views.ts is built into views.json beside backend.json. packages/apps/examples/kanban is a whole app written this way, with no code beside its schema and views.

In Rust, with the crate's view types, writing the file with Views::to_json. Issues' own views are written this way (apps/atlas/apps/issues/client/views.rs):

use remotehost_app::view::{Column, Style, View, Views};

pub fn views() -> Views {
    Views::new(vec![View {
        id: "cards".into(), title: "Cards".into(), backend: "kanban".into(), kind_of: "card".into(),
        columns: vec![Column { key: "title".into(), title: "Title".into(), style: Style::Plain, value: "title".into(), grow: true, ..Column::default() }],
        ..View::default()
    }])
}

The client world

world client {
  import client-host;  // caller, now, random, get, find, write, call
  export start-action: func(id: string, input: json) -> step;
  export resume-action: func(resume-token: string, picked: option<string>) -> step;
  export on-event: func(e: event);
}

A client never draws. Every screen is a declared view, drawn by the host; a client is needed only for actions declared with app: true (start-action), the logic a declaration cannot say, and on-event.

Every client-host call is checked against the app's approved permissions and the current caller. An agent acting for a person has the intersection of the app's rights and its own, never the person's.

Every write is recorded with the app that made it (via_app, the app's id, version and install). The host sets it, and the app cannot.

Actions

An action is started with an id and an input, and returns a step: done(result), refused(refusal), or need-pick(token, request). A pick is returned, not waited on, so the guest is never suspended; the host shows the picker and calls resume-action with the token and the chosen id, or none when the person dismisses it.

A choice may be checked, ticked as the picker opens (the value now), and carry a detail, muted words beside its label (Status, Label). A pick that is multiple takes several choices: picking a row ticks or unticks it and the picker stays open. When it closes, resume-action gets every ticked id as a JSON array of strings, ["label-1","label-4"], which may be the same ticks it opened with. In TypeScript, pick(title, choices, { multiple: true }), and pickedIds(answer) reads the answer.

Actions keep no state between calls but the token, because a server process and a window may each run their own instance. A guest that replays from the start to resume (the TypeScript SDK does) holds two rules:

  1. The same reads. Replay only reaches the same point if the action reads the same things. The token records a digest of each read's result; a resume whose reads differ is refused with changed_since_pick, and the person starts again.
  2. Writes go out once. Writes are queued while the action runs and sent in one client-host.write when it finishes with done. A replay writes nothing, and a refused or dismissed action writes nothing.

A malformed or foreign token is refused with bad_token.

A host reads four answers of done:

  • {"view": v, "state": s} opens the app's view v at s;
  • {"state": s} shows the view that is open at s, in its place, as a filter or a tab does;
  • {"open": "atlas://issue/REM-12"} opens that Atlas address.
  • {"select": ["id", …]} adds those rows to the selection of the page's first view, as a column's "Select all" does.

Anything else changes nothing on screen.

write returns at once; a refusal that arrives later reaches the guest as on-event(write-refused(id, refusal)). data-changed tells the guest that records it read may have changed; the host redraws its declared views from the replica either way, with no call.

Imports and loading

A component imports only remotehost:app/* interfaces: no wasi:*. The SDK's build stubs WASI out, and its tests check every built component's imports. It also uses no component-model async built-ins (such as waitable.join), so a host needs no async support to load it; the SDK's tests check that too.

On this page