---
title: "Components and actions"
description: "A component may write some of its members in other files (LLP 1091.002), so a large root can be split by feature under the line cap."
modificationDate: "2026-11-30"
---

> ## Documentation index
> Fetch the complete documentation index at: https://exact.expo.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Components and actions

<AgentInstructions>

## Submitting feedback

From the app's directory, read `bun exact.mjs feedback status`. Under `never`, keep no note.
Respect `EXACT_FEEDBACK=0` and do not change the policy.

Otherwise record specific, actionable feedback with:
`bun exact.mjs feedback note "Exact docs: https://exact.expo.dev/reference/contract-grammar/components-and-actions: <what was wrong or missing>"`

The note goes to Expo only as that status allows. Include no secrets or personal data.

</AgentInstructions>

```ebnf
component     = "component" IDENT block(section) ;
section       = "props" block(field)
              | "inject" block(field)
              | "provide" block(provider)
              | "slot" NL
              | "state" IDENT [ ":" type ] "=" expr [ "persist" ] NL
              | "derive" IDENT "=" expr NL
              | resource | mutation | action | task | sequence
              | "members" STRING NL
              | "view" block(node) ;
members-block = "members" IDENT block(member) ;
member        = "state" IDENT [ ":" type ] "=" expr [ "persist" ] NL
              | "derive" IDENT "=" expr NL
              | resource | mutation | action | task | sequence ;
provider      = FIELD [ "=" expr ] NL ;
resource      = "resource" IDENT "=" source-call
                [ "for" IDENT "in" expr [ "key" "=" expr ] ]
                [ "with" expr { "," expr } ] [ "when" expr ] "as" "shape" type
                [ "else" source-call ] [ "transient" | "keep" ] NL ;
mutation      = "mutation" IDENT "as" "shape" type [ "queue" | "parallel" ]
                [ "refreshes" IDENT { "," IDENT } ]
                [ "then" IDENT ] NL ;
action        = "action" IDENT [ "(" [ action-params ] ")" ] block(statement) ;
action-params = action-param { "," action-param } [ "," ] ;
action-param  = IDENT [ ":" type ] ;
task          = "task" IDENT ( "mount" | gate ) block(schedule) ;
gate          = "when" expr [ "key" "=" expr ] | "key" "=" expr ;
schedule      = "every" "(" "frame" "," IDENT ")" NL
              | ( "every" | "after" ) "(" expr "," IDENT { "," timer-option } ")" NL
              | "change" "(" IDENT ")" NL ;
timer-option  = "wait" "=" ( "frame" | "update" | "scrollend" | "idle" )
              | ( "max" | "tolerance" ) "=" NUMBER ;  (* max needs wait=scrollend or idle; tolerance excludes wait *)
sequence      = "sequence" IDENT ( "mount" | gate ) block(play) ;
play          = "play" "(" expr { "," IDENT "=" expr } ")" NL ;
statement     = IDENT "=" expr NL
              | "let" IDENT "=" expr NL
              | "send" IDENT "=" source-call NL
              | "refresh" IDENT NL
              | IDENT "(" [ arguments ] ")" NL
              | if
              | statement-match ;
if            = "if" expr block(statement) [ "else" ( if | block(statement) ) ] ;
statement-match = "match" expr block(statement-case) ;
statement-case  = "case" "some" "(" IDENT ")" block(statement)
                | "case" "none" block(statement) ;
source-call   = IDENT "(" [ arguments ] ")" ;
```

A component may write some of its members in other files (LLP 1091.002), so a
large root can be split by feature under the line cap. `members
"./composer.contract"` in its body stands for the members that file declares
under `members Name`, as if they were written at that line: the program, and
the plan, are the one-file program's. The path is a relative `use` path
(`contract-use-path`). A members file holds one `members` block, named for the
component that lists it (`contract-members-owner`), listed by one line
(`contract-members-twice`, `contract-members-unlisted`); the block holds
`state`, `derive`, `resource`, `mutation`, `action`, `task` and `sequence`,
and the once-only sections and `members` lines stay in the component's own
body (`syntax-members-section`). Every file of a component sees all its
members, props and injects; a name declared in two of its files is refused
naming both (`contract-members-duplicate`). Any other name a members file
calls (a shape, a `fn`, a component) comes from its own `use` lines or is
declared in it, beside the block; another file, the root among them, names
such a declaration on a `use` line. The
component's rules hold for its members wherever they are written: a child's
members file may declare resources, mutations and tasks at bounded uses.

There is one `props`, `inject`, `provide`, `slot`, and `view` section at most in
a component. Any component may own resources, mutations and tasks (LLP 1035.005.004): each instance of a child asks for its own
resources, after the render that makes it, and lets go when the render destroys
it. Each instance sends its own mutations: its own `pending`, failure, queue and
answer, and its `then` runs in that instance, where it may call an action prop.
A child's `refreshes` names its own resources. A send in flight when the render
destroys the instance stays sent, but its answer changes nothing and its `then`
does not run, and its waiting sends are dropped. A child's resource is not a
resource over a list, and a child that owns requests or tasks is used where its instances
are bounded: outside every region, under `if` and `match`, or in a row of
`stack(nav)`, `t.stack` or `nav.tabs`, never under another `for` or in a
virtualized list (`type-child-resource`). Its state initializers do not read its
own resources, nor does a state initializer of a component it uses outside any
`if`, `match` or `for` of its own read its resources or mutations through a prop
(`type-state-reads-request`). The device's facts are sources a
component declares, the root or a child: `resource v = exactViewport() as shape
V` (or `exactPage()`), with no arguments and no `else`, opens no request, and
every instance reads the root's one answer (`EmptyState` reads
`accessibilityTextSize`). A `derive` reads the resource's field (`v.width`), never
`exactViewport().width`. A viewport shape can declare either of the screen
orientation fields. The resource updates when the screen turns.

| Field on the viewport shape | Value |
| --- | --- |
| `orientationType: string` | `portrait-primary`, `portrait-secondary`, `landscape-primary` or `landscape-secondary` |
| `orientationAngle: number` | Degrees from the screen’s natural orientation, one of 0, 90, 180 or 270 |

A task's body has exactly one schedule. Each child's task starts with
its instance, stops when the instance is destroyed and runs its action in that
instance's frame. A hidden tab or covered screen can remain alive: gate its
work on activity. Frame tasks are allowed, with one action per armed instance
per frame. Reload restarts timers over the carried state. A gated task (`when cond`, LLP 1092) has its
timer only while `cond` holds, armed from the commit that made it true; `key=`
re-arms it from the commit that changed the key (compared as a `for` key),
and `key=` alone is `when true key=…`. The gate is a bool (`type-task-gate`), the
key a string, number or bool (`type-task-key`), and neither reads `performanceNow()`,
directly or through a derive or a `fn` (`analyze-task-gate-clock`). The named timer action takes no parameters;
a millisecond interval is a literal whole number of at least 1.
A `change(action)` schedule requires `key=` and accepts no timer options. It queues
one action after the first active commit, a changed key or a reopened gate. Pending
changes coalesce, a closed gate cancels them, and a refused action waits for another
key change or activation. The host applies each preceding commit before the action
runs; the virtual clock need not move. Cycles through change actions and their
trigger inputs are refused (`analyze-change-cycle`).

A `sequence` (LLP 1125 D2) declares what should play, as a value, and the
runner plays it: the gate is a task's, and its body is exactly one
`play(tracks, bpm=, from=, countIn=, clock=, clockOut=, ended=)`
(`contract-sequence-body`).
`tracks` is a list of a shape whose fields are, in order, `beats: number`
(the track's length, which it loops at), `loops: number` (0 is forever),
`offset: number`, `output: string` and `steps: S[]`; a step's shape `S` has,
in order, `beat: number` (from the track's start, in quarter notes),
`src: string` (a declared sound, or `""`), `gain: number`, `group: string`,
`note: number`, `velocity: number`, `channel: number`, `duration: number`,
`haptic: string` (a `haptic()` kind, or `""`), then optionally
`playbackRate: number` and `pan: number` (`type-sequence-play`, which also
types the options and refuses an unknown or repeated one). `bpm=` is
required unless `clock=` is given; `from=` (default 0) is the beat at the commit that armed it, and
below 0 it is a count-in: `countIn=`'s steps play once over `[from, 0)`, their
beats counted from `from`. `ended=` names a parameterless action run when the
last finite track ends, at that time. The gate, key and arguments read no
`performanceNow()` (`analyze-task-gate-clock`, `analyze-sequence-clock`), and
only the root declares one (`type-child-resource`). The arguments are read
again after every commit that stands: an equal value changes nothing, and a
different one ends the sequence's voices that have not started (`by edit`)
and plays the new value from that commit, a new `bpm` without a jump in
phase. A step whose `note` is not −1, on a track whose `output` names a MIDI
output, is a note-on there (`velocity` 1–127, `channel` 0–15) and a note-off
`duration` beats later (on `output=""`, no output, it goes to no device and
`exactMIDI().sent` lists it with `output: ""`); a track's `offset` (within ±500 ms) moves its
samples', notes' and haptics' times, as a latency is lined up by ear.
`clockOut="<output id>"` sends Timing Clock 24 times a beat, Start before the
first tick at a beat at or after 0, and Stop at the stop or the end
([MIDI](https://exact.expo.dev/reference/contract-grammar/components-and-actions.md#midi-exactmidi-sendmidi-midimessage)). `clock="<input id>"`
follows that input's MIDI clock instead (LLP 1125 D9): the sequence is
`waiting` until the input sends Start, which puts beat `from` at the next
tick; its tempo comes from the last 48 ticks' timestamps (`bpm=`, default
120, until 13 have come), its position counts ticks, and a hit not yet within
50 ms of being due that a new tempo or phase moves by more than 2 ms is taken
back (`by clock`) and played again. Stop silences it as the gate would and
leaves it `waiting` (reason `clock`); Continue resumes at the Song Position
sent since, else where Stop held it. The input is opened whether or not an
element hears it, and its Start, Continue, Stop and Song Position are still
heard as `midimessage`. A sequence that follows a clock sends none
(`clockOut=` is ignored and journaled), and a changed `clock=` restarts it,
as a changed key does. One
sequence plays at a time; leaving the foreground on iOS stops it (reason
`background`) unless `audio_session` is `playback` or `playback-mix` with `audio` in
`host.ios.backgroundModes`. `resource t = exactTransport() as shape T` reads
it: `state` (`stopped`, `waiting`, `countin`, `playing`), `reason` (`gate`,
`ended`, `background`, `bpm`, `clock`, or `""`), `bpm`, `anchorAt` and
`anchorBeat` (the beat now is `anchorBeat + (performanceNow() - anchorAt) *
bpm / 60000`) and `clock` (`internal`, or `midi` while following, when the
tempo is rounded to 0.1 and it and the anchor are said again only when they
move by 0.5 bpm or 1/48 of a beat, or the state does); it is answered by a
commit of its own after each change, as an answer's `then` runs.

## Live Activities: `startActivity`, `updateActivity`, `endActivity`

The three reserved mutation sources (LLP 1126.001 WP9) compile on every host.
They run on iOS through an ActivityKit arm loaded at first use, and on Android,
for an entry with an `android` mapping, as an ongoing notification (LLP 1126
D13; reference.md "Live Activities"); other hosts refuse the send with `… is
not linked into this artifact`.
Declare the entry in `app.json`'s `live_activities`, its state shape and slots
as in `apps/caltrain/activities.contract`. Each send answers a record whose only field is
`id: string`; the compiler refuses other result shapes:

```contract
shape DepartureState
  status: string
  at: number
shape ActivityHandle
  id: string

component App
  mutation activity as shape ActivityHandle
  action follow(state: DepartureState)
    send activity = startActivity("departure", state)
  action delay(id: string, state: DepartureState)
    send activity = updateActivity(id, state, some("Train delayed"), none)
  action finish(id: string, state: DepartureState)
    send activity = endActivity(id, state, "immediate")
  view
    text "Train"
```

`state` is a record, checked against the entry's state shape at runtime.
An update's optional third argument is `option<string>` (the alert's title,
with the default sound); its optional fourth is `option<number>` (the stale
date in Unix milliseconds). Ending takes `"default"`, `"immediate"`, or a
Unix millisecond dismissal date. A string policy must be one of those literals
or an `enum<"default", "immediate">` value; arbitrary strings are refused at compile time. Attributes plus state obey the same 4 KB
bound as the bake. Update and end validate against the generation in which
the activity started. Keep that state shape while its activities are alive; a
new shape cannot update or end an older instance with incompatible state. A
compatibility-changing binary update follows LLP 1126.001 §5 Q6’s device gate.

`resource activities = exactActivities() as shape Activities` reads a record
whose fields are `activities: Activity[]`, `frequentPushesEnabled: bool`,
`linked: bool` (the host packaged its arm), `pushToStartToken:
option<string>` and `pushToStartActivities: PushStartActivity[]`.
An activity has `id`, `kind`, `state` (a JSON string), `activityState`
(`pending`, `active`, `stale`, `ended`, `dismissed`), `token: option<string>`
and `promoted: bool`, true when Android posted its notification as a promoted
Live Update (`FLAG_PROMOTED_ONGOING`; false elsewhere).
A push-start activity has `kind`, `generation` and `shape`, all strings.
Readers may name only the fields they need. Off iOS and Android the lists are
empty; off iOS the push-to-start token is absent and frequent pushes are false.
Android lists the activities its `app.json` row maps (`android`, reference.md
"Live Activities"). A first demand
enumerates existing activities, including after a relaunch without a send;
later token, state and content updates re-answer the source. A token is absent
until ActivityKit supplies it, and exists only for an entry declaring
`push: true`. The data module sends it to its own backend. The
`remote-notification` background mode stays refused; an app with activities
registers for remote notifications only when it grants `device.push`.

Push-to-start (iOS 17.2 and later) lets the app's backend start an activity
while the app is not running (LLP 1126 D9). `pushToStartToken` is
ActivityKit's push-to-start token, read only when an entry declares
`push: true`; it is absent until ActivityKit supplies one, which it does
once Live Activities are allowed, and the source answers again when it
rotates. `pushToStartActivities` lists the entries declaring `push: true`, each
with the `generation` the app runs and its state `shape` digest; it is empty
until the app has published that generation, just after it starts. The backend
sends APNs a `start` event with `attributes-type` `ExactActivityAttributes`,
`attributes` `{"kind", "generation", "shape"}` from that list, and
`content-state` `{"shape", "state"}`, the same shape digest and a state in
the entry's declared shape
([Apple: starting a Live Activity with a push](https://developer.apple.com/documentation/activitykit/starting-and-updating-live-activities-with-activitykit-push-notifications)).
It sends the values the app last reported, since a delivered update changes
the generation; a generation from before a compatibility-changing binary
update no longer renders.

No app code runs when the start arrives. iOS may launch the app in the
background for it, and the host boots no session for that launch. The started
activity, with its update `token`, appears in `activities` the next time a
session reads `exactActivities()`: at once in a session already reading it,
otherwise at the app's next launch. Until then the backend has no update token
for the activity, so it cannot update or end it. The app can update and end
it as it does an activity it started.

## MIDI: `exactMIDI`, `sendMIDI`, `midimessage`

MIDI is Web MIDI's, by its names (LLP 1125 D6–D8), and needs the grant line
`device.midi <strings key>` on every host (`Permissions-Policy: midi` on the
web); without it `state` is `denied` and a request is refused by name.
`resource m = exactMIDI() as shape M` reads `state` (`prompt` until
`requestMIDIAccess()` asks, then `granted`, `denied`, or `unavailable` where
there is none: WebKit, tvOS, Linux and Windows), `inputs` and `outputs`, each
a list of a port shape of `id` (stable across replug), `name`,
`manufacturer` and `state` (`connected`, `disconnected`; a port seen stays
listed), and `sent`, the last 128 messages that went out, in the order they went, each
`output`, `data` and `timeStamp` (runner ms; no Timing Clock, nothing taken
back) — any other field is refused at the bake (`bake-midi-field`). It
changes by itself as ports come and go, and, when it declares `sent`, as each
message goes. `requestMIDIAccess()` takes no
arguments (`type-request-midi-access`). `sendMIDI(output, data, at=)` sends
`data`, the bytes of one or more whole MIDI 1.0 messages (no running status,
no SysEx; a literal one is checked, `type-send-midi`), to an output by `id`
at `at` on the runner's clock (the commit's time by default, and the past is
now); what is not well-formed, an output not connected, or the 1,025th
message waiting is dropped and journaled (note-offs and Stop never are).
`""` is no output: what is sent there reaches no device, needs no access, and
`sent` lists it with `output: ""` (an activity log with no device, LLP 1125 D6). The
runner keeps the queue: a host hands a message to its output 50 ms before it
is due and holds it until then, so an edit or a stop takes back what is
still held, and a note already handed still gets its note-off. A sequence's
notes and clock go through the same queue.

`midimessage=action` on an element with `midiinputs=["<input id>", …]` hears
each message from those inputs; every mounted element that declares it hears
it, in tree order, each in its own commit. Its action may take a
`MIDIMessageEvent`: `input`, `data` (`number[]`), `timeStamp` (runner
milliseconds) and `beat` (the sequence's beat then, −1 while stopped or
waiting for a clock). Control Change, pitch bend and pressure keep only their
latest value within one delivery, never across a note of the same input and
channel; notes and transport messages are never dropped or reordered; Timing
Clock and Active Sensing are not dispatched (a followed input's ticks go to
its sequence). `onMIDIMessage` and `midiInputs` are refused with
these names.

`else if c` is `else` around one nested `if c`, in an action and in a view
alike: the same tree, so the same plan. A view refuses `when` and `each`
(`syntax-view-keyword`) and `else when` (`syntax-else-keyword`), naming the
edit.

Both option-match arms are required exactly once. Actions have no loops, returns,
or awaits. A standalone call statement `name(args)` is a host command when `name`
is one. When `name` is also an action, an `action` prop or an injected
action of the component the statement is written in, the call is refused
(`syntax-call-ambiguous`, LLP 1089 D1), inside an action of that name too:
rename the action (Caltrain's wrapper is `action chooseScheme`, which calls
the command `setScheme(s)`). When `name` is not a host command, it calls an action of the same component, an
`action` prop or an injected action (LLP 1089), never a function. A call is
expanded in place: the callee's statements run where the call stands, in the
caller's one commit, reading the state the action started with. Its arguments
complete the callee's parameters after any curried where it was bound; no event
payload is appended. A call gives no value (`type-call-value`), passes no action
as an argument (`type-call-action-arg`), and never recurses, directly or through
other actions (`syntax-call-cycle`). An action whose calls would expand past
1,024 statements is `syntax-call-size`. `let` is recognized as the
local-declaration statement when followed by a name; a writable slot named `let`
can still appear in an ordinary assignment.

A resource's optional `with` supplies one or more request context expressions,
after its call arguments and before `as shape`. The source receives both lists
in order. A change to either asks again. If the source returns the same single
request it has in flight, its reply is parsed with the newest arguments. Any
change to `with`, including one alongside a changed call argument, earns one
ordinary follow-up when a kept plain HTTP read lands or fails. A change confined to
call arguments earns none. Uploads and streams follow their existing rules. Admission of an eligible persisted answer at boot
(LLP 1027.005) and `current` (below) compare the call arguments alone. The call
may be empty. `with` requires at least one expression. `else` follows the shape.

A resource's optional `when cond`, before `as shape`, asks it only while `cond`, a
`bool`, holds (LLP 1161.002; `type-when-not-bool`). While it is false the resource
is idle: nothing is asked, a request in flight is let go (an upload's goes on),
`pending` and `failed` are false and `failure` is `none`, and `refresh` asks
nothing. It keeps the value it showed, which is no longer an answer: `current` is
false. When `cond` turns true the resource is asked again, forced, even at the
arguments it had, and is current once that answer lands. A resource idle at boot
shows its placeholder, or an answer the boot starts with: a rendered page's for it,
or one a native host kept; `current` is false either way. A resource over a list
takes no `when` (`syntax-resource-for-when`).

A resource over a list, `resource r = source(x) for x in list as shape S`,
asks its source once for each element (LLP 1017.000 P4c, amended
2026-11-04). Each request is keyed as a `for` row is: by `key=`, or, without
it, by the element, which must then be a string, number or bool
(`type-resource-for-key`). The arguments and the key read the element. An
element that joins starts its request, one that leaves lets only its own
request go, and the others go on. `r` reads as `S[]` in the list's order,
each element its shape's zero until its answer; an element whose key
repeats an earlier one's reads that one's answer. `pending(r)` and
`failed(r)` are true when any element's request is pending or has failed,
`current(r)` when every element's is, and `failure(r)` is the first failure. It takes no `with` or `else`
(`syntax-resource-for-with`, `syntax-resource-for-else`), and asks a data
source, not one the runner answers (`lower-resource-for-source`). A
mutation's `refreshes r` shows the source's overlay over each element from
the send, and asks every element again when the reply lands. Each element
retires the write independently once its answer was asked after the landing,
unless its overlay keeps it; leaving the list also retires it.

A resource's `else` is a placeholder. `else empty()` is the resource type's zero,
with `field=constant` overrides for a record. `else source(values…)` names a source
whose arguments are plain values, not state; it is answered once at build.
`transient`, last on the line, keeps the answer out of the device's storage: no
launch shows it before the source answers, and an answer kept before is
forgotten (LLP 1156.005 D4). `keep`, in the same place, marks an answer to keep:
an `exactSurface` reader's record (LLP 1156.005 D5) and, in an app whose grants
otherwise keep no answers (Health, contacts, a calendar, the photo library), a
data source's answer or that of a module source declared `kept` (LLP
1069.008.000 D7). It is refused beside `transient`, over a list, and on a source
declared in Contract, a runner fact or any other native module source
(`lower-resource-keep`).
A mutation's `then` names a parameterless action and follows `refreshes` when
both are present. `queue`, right after the shape, makes every send of the
mutation wait its turn (LLP 1092): one request in flight, later sends asked in
order, each after the reply before it and its `then`. `parallel`, in the same
place, asks every send when it is made (LLP 1161.000): each is its own request
in flight, at most 64 at once (the 65th refuses its action, `QueueFull`), and its
reply lands whatever else is out. A reply lands in the slot unless a later send
has already concluded (answered or failed), `pending(m)` is true while any send
is out, and an assignment forgets no request. A `parallel` mutation takes no
`then` (`type-parallel-then`): its replies land in any order. Its source is
called once per send and may have several calls outstanding; a source that reads
local storage, changes it and writes it back orders its own work or is `queue`.
With neither, a send forgets the one in flight: the newest wins. The clauses after the shape
may continue onto deeper-indented lines, each starting with its keyword, in the
same order (`mutation edited as shape Jump refreshes page`, then `then followEdit`
indented under it). Action effects are inferred: `writes` clauses are refused.
Component `contract` sections are also refused.
