# Usage

What people do in a program: which screens they open, which actions and
calls they use, what fails, who comes back, and measures of the program's
own (`track`); and the web's own numbers a site's owner looks for in Google
Analytics or Plausible: visitors, visits, pageviews and bounces, where visits
came from, the country, the browser and device, goals, who is here now and
how fast each page loaded. Kept in the program's own database and shown on
its own admin page. Optional, off unless said, nothing leaves the back end,
and by default no IP address is kept and no lasting id is stored in the
browser ([what is collected](#what-is-collected)). Every event kept one by one and asked
of later (funnels, retention, paths, people, flags, experiments, ClickHouse) is
[analytics.md](analytics.md). Back to the [map](README.md).

```mote
app "Shop" usage=on
use "pkg:usage/usage.mote"

// Who may read usage: this program's answer.
fn usageMay(): bool
  let me = auth.me()?
  return me?.email == "owner@shop.example"

// What counts as a visit reaching what it is for (optional).
fn usageGoals(): string[] = ["checkout", "/thanks"]

action checkout
  track("checkout", {plan: cart.plan, total: cart.total})

route "/admin/usage"
  UsagePanel
  UsageChart event="checkout" by="plan" last="30 days"
```

```toml
# mote.toml, beside the entry
[packages]
usage = "../mote/extensions/usage"
```

That is all of it. With those lines the admin page shows visitors, visits,
pageviews, pages a visit, the bounce rate and the time in front against the
span before; the pages with their entrances and exits, the sources and
campaigns, the countries, the devices and browsers, the goals, who is here
now and how fast each route loaded; then people active today, this week and
this month, the screens, actions and calls most used with how often each
fails and how long it takes, what `track` was told, and who came back week
by week.

## Mental model

There are two parts, and only the first is in Mote itself.

- **The seam** (the compiler and the runtime). The runtime already sees a
  screen shown, an action run, a call answered, a sign-in, a job's run. With
  `usage=on` it gathers them, with what `track(…)` says, and hands them to
  the program's own code: `server on usage(batch)` + a block, every five
  seconds. It keeps nothing itself.
- **The extension** (`extensions/usage`, ordinary Mote in a
  [package](language.md#packages)). It has the `server on usage` block, the
  models the events are kept in, the questions asked of them as `server
  fn`s, and the panel's components. It is not in the compiler: a program
  takes it with `use`, and can read it, change it, or write its own.

**Without both `usage=on` and a `server on usage` block nothing is gathered
and nothing of this is built**: the page and the back end are byte for byte
what they are without it, and a `track(…)` line compiles to nothing.

## Turning it on

| On the `app` line | |
|---|---|
| `usage=on` | Everyone is counted: people signed in by their id, others by a random id their browser makes. |
| `usage="signed in"` | Only people signed in. A browser nobody is signed in on makes no id; it is told so by the back end the first time it sends anything, and holds off for a minute at a time. |
| `usage=off`, or nothing | Off. |
| `dnt=ignore` | A browser that asks not to be tracked is counted all the same ([below](#what-is-never-gathered)). |
| `visitors=kept` | Someone signed out is the same visitor when they come back: their id is kept for a year. Unsaid: until the browser is closed, so only people signed in are ever "returning" ([cookies](#cookies-and-consent)). |
| `paths=full` | A screen's address is kept as it is (`/job/42`). Unsaid (`paths=named`): with the route's `:name` parts, and any part that looks like an id, put back as names (`/job/:id`), since an address can carry an id or an email address. |
| `geo=city` | A region and a city as well as the country, where a proxy in front says them ([below](#where-people-are)). `geo=off`: nothing of where, not even the time zone. Unsaid: `geo=country`. |
| `vitals=10` | One page load in this many says how fast it was ([speed](#speed)). `vitals=all`, `vitals=off`. Unsaid: 10. |
| `autocapture=on` | Presses on controls, fields changed (never what they hold), rage clicks and dead clicks are noted too, with no line written for them ([below](#autocapture)). Unsaid: off. With usage off it is nothing. |

`usage=on` with no `server on usage` block anywhere is refused (`H151`):
take the extension, or write a block.

## What is gathered

One event for each of these, with no line written for it:

| `kind` | When | `name` | Also |
|---|---|---|---|
| `"screen"` | a `route` is shown (a page with no routes: once, when it opens): each a pageview | the route as written: `/job/:id` | `path`, `title`; on the first of a page's loading `referrer` and `utm` |
| `"leave"` | that route is left, or the page hidden | the same | `ms`: how long it was in front, engaged; `path` |
| `"vital"` | a page measured how fast it loaded, as it is first hidden ([speed](#speed)) | the route it loaded on | `props`: `lcp`, `cls`, `inp`, `ttfb` |
| `"action"` | an action has run | its name | `ms`, `ok`, `failKind` |
| `"failure"` | a failure nothing in the page heard ([what `on failure` hears](back-end.md#when-something-fails)) | where it came from: the call, the action, `page`, `resource`, `live` | `failKind` |
| `"track"` | the program said `track(…)`, in the page or on the back end | what it said | `props` |
| `"call"` | the back end answered a call a page made: a `server fn`, or a model's write (`Order.add`) | its name | `ms`, `ok`, `failKind` |
| `"signin"`, `"signup"` | `auth.signIn`, `auth.signUp` succeeded; or the program's own code signed someone in (`auth.signInAs`: a reset link, [Google](google.md)) or made their account (`auth.create`) | the kind | `anon`: the id the browser had until then, so what it did signed out is the account's ([below](#a-visitor-who-signs-in)) |
| `"job"` | a [`job fn`](back-end.md#later-job-fn) ran | its name | `ms`, `ok`, `failKind` |
| `"here"` | a tab's [open line](#the-open-line) opened, its route changed, it was shown or hidden, and every 30 seconds while it is open | the route in front | `route`, `path`, `props`: `{visible}` |
| `"gone"` | that line closed and no line of the tab opened again within 30 seconds | the route it was on | `ms`: how long the tab was here; `at`: when it closed |
| `"click"` | with `autocapture=on`: a press on a control ([below](#autocapture)) | the control's `data-mote` name, else its tag | `props`: `{tag}` |
| `"change"` | with `autocapture=on`: a field changed | the field's `data-mote` name (or `name`), else its tag | `props`: `{tag, type}`, never what it holds |
| `"rage"` | with `autocapture=on`: three presses or more within a second, within 30 pixels | the control's name, or `page` | `props`: `{tag}` |
| `"dead"` | with `autocapture=on`: a press on a button or a link after which nothing on the page changed for a second and a half | the control's name | `props`: `{tag}` |

- A page's events carry the `route` they happened on, the page's `session`
  (a random id for that tab) and, for someone signed out, `anon`: the
  visitor's random id (a cookie, `mote_visitor`), and `client`: what the
  browser is and where it is ([below](#what-is-collected)).
- **`user` is who the session says is signed in.** It is set by the back
  end from the cookie, on a page's events as on a call's. Nothing a page
  sends says who it is.
- A model's reads (`find`, `get`, `count` …) are not events, nor is a `live`
  value worked out again, a call that was refused before it ran (`requires`,
  a wrong argument, no such call). A row added or changed is counted as the call that did it
  (`Order.add`), with nothing of the row; for more, say `track`.

## What is collected

Every field kept, what it is unless something says otherwise, and whether it
is personal data. (In the sense of the GDPR: something that, with other
things, can be tied to one person. A visitor's random id is personal data,
however random; a count of visits by country is not.)

| Field | Default | Changed by | Personal data |
|---|---|---|---|
| the route a screen is (`/job/:id`), an action's, a call's, a job's name | on | `usage=off` | no |
| the screen's address, with ids put back as names (`/job/:id`, `/search/:id`) | on | `paths=full`: as it is (`/job/42`) | no; with `paths=full`, it can be |
| the page's title (`document.title`, 80 letters) | on | the program's titles | only if a title holds a name |
| where a visit came from: the other site's host (`www.google.com`), never its address | on | — | no |
| the landing address's `utm_source`, `_medium`, `_campaign`, `_term`, `_content` (60 letters each) | on | — | no, unless a link puts a person in them |
| time in front (visible and focused) on each screen | on | — | no |
| who: an account's id; for someone signed out a random id | on | `usage="signed in"`: accounts only | yes |
| how long that random id lasts in the browser | until the browser is closed | `visitors=kept`: a year | yes |
| country (ISO 3166-1 alpha-2), from a proxy's header, a file of address ranges, or the time zone | on | `geo=off` | no (a country of millions) |
| region and city | off | `geo=city`, and a proxy that says them | can be, in a small place |
| the browser's time zone and language | on | `geo=off` (the zone; the language stays) | no |
| browser and its major version, system, device (desktop, tablet, phone) | on | — | no |
| the User-Agent, the browser's own name for itself (Client Hints) | read at the door to say the above; handed to `server on usage` blocks, not kept by the extension | — | it is fingerprinting matter: a block of one's own should not keep it |
| screen and window width (5 buckets), pixel ratio (4 buckets) | on | — | no |
| whether a program drives the browser (`navigator.webdriver`) | read, to leave it out | `USAGE_AUTOMATION=count` (tests) | no |
| how fast a page loaded (LCP, CLS, INP, TTFB) | 1 load in 10 | `vitals=` | no |
| whether a tab is open and shown, the route in front, how long the tab was here (the [open line](#the-open-line)) | on | — | no (it is kept with the visitor's id, as the rest is) |
| a press on a control, by the control's name and tag; a field changed, by its name and type | off | `autocapture=on` | no; never what a field holds, nor a control's words |
| where on the page a press was | looked at in the page only, to say a rage click | — | — (never sent) |
| `track`'s properties | what the program says | the program | what the program makes them |
| **the IP address** | **never kept, never logged by usage** | — | — |

**The IP address** is read only at the door (`POST /rpc/usage.send`), as the
server knows it, to look up a country in `MOTE_GEO_DB` and to bound how much
one address may send; it is in no event, no row and no line of the log the
usage door writes. (The run `tests/e2b_web` searches the databases' bytes
and the logs for the addresses it came from: none.)

### What is never gathered

- The values of a row's fields, what anyone typed, a failure's words.
- An address's query, a referrer's path, an IP address.
- Anything from a browser that sends Do Not Track or Global Privacy Control:
  its page gathers nothing, makes no id and sends nothing (unless
  `dnt=ignore`). The back end does the same: a call, a sign-in, a sign-up
  or a `track` in a request that says so (`Sec-GPC: 1`, `DNT: 1`) is
  counted by name, and for nobody, signed in or not.
- Anything of someone [acting as another](back-end.md#acting-as-someone).
- A program that is not a person: a crawler, a monitor, a script, a browser
  a program drives ([below](#bots)).

### Cookies and consent

**With the defaults, nothing lasting is stored in the browser.** The page
keeps three things, all gone when the browser (or the tab) is closed:

| Where | Name | What | For how long |
|---|---|---|---|
| a cookie | `mote_visitor` | a random id, for someone signed out | until the browser is closed (no `max-age`) |
| `sessionStorage` | `mote_usage` | a random id for the tab | until the tab is closed |
| `sessionStorage` | `mote_usage_path` | the address in front, as sent (`/job/:id`) | until the tab is closed (so a reload is no second pageview) |

A browser that restores its last session ("continue where you left off")
keeps a session cookie across restarts: that is the browser's choice, and
the cookie still says nothing but a random id.

**With `visitors=kept`, `mote_visitor` lasts a year**: a long-lived
identifier on the device, used for counting. In the EU that typically needs
consent (the ePrivacy rules on storing things on someone's device), and a
program that says `visitors=kept` should ask for it. With the defaults, some
regulators (France's CNIL, for one) exempt first-party audience measurement
that keeps to their conditions; whether a site needs a banner is its
owner's legal call, not the compiler's. What Mote does: no third party, no
lasting id unless asked, no IP address, Do Not Track and Global Privacy
Control honoured.

**Returning visitors** therefore need `visitors=kept` for people who are
signed out: without it, a visitor's id ends with the browser's session, and
whoever comes back the next day is new. People signed in are counted by
their account and are returning whatever the setting.

## The web's numbers

What a site owner reads in a web analytics tool, kept by the extension from
the events above (`extensions/usage/visits.mote`).

**A pageview** is each screen shown: each route change, in a page that
routes (an address after `#`); once, in a page that does not. A reload of
the screen in front is not another pageview. A pageview has the route's
pattern (`/job/:id`, as `UsageTop` counts screens), the address
([`paths=`](#turning-it-on)) and the title.

**A visit** (a session) is what one browser does with no gap of
`USAGE_SESSION_MINUTES` (30) in it: the next thing done after a longer
gap, or after midnight where days are counted (`USAGE_ZONE`), begins
another. One browser is one `who` (an account, or the random id), across its
tabs. A visit's first pageview is its **entrance**, its last its **exit**.

**A bounce** is a visit of one pageview, under 10 seconds in front, that
reached no goal. (GA4 counts the other way round: an "engaged session" is
one of more than 10 seconds, or of 2 or more pageviews, or with a
conversion; a bounce is a session that was not engaged. The two agree.)
The bounce rate is bounces over visits.

**Time in front** (engaged time) is how long a screen was visible and its
window had the keyboard (`screen.visible` and `screen.focused`), not how
long it was open; it is said when the screen is left or the page hidden. A
visit's is the sum of its screens'.

### Where visits come from

The page sends, with the first screen of each loading, the host of
`document.referrer` (`www.google.com`; `self` for this site's own; nothing
for none) and the landing address's `utm_` words. A visit takes them from
its first event:

| Class | When |
|---|---|
| `direct` | no referrer and no `utm_source` |
| `internal` | the referrer is this site |
| `search` | the source is a search engine's: Google, Bing, DuckDuckGo, Yahoo, Yandex, Baidu, Ecosia, Startpage, Qwant, Naver, Seznam, Kagi, Ask, AOL, Sogou, Brave, Daum, Mojeek, Perplexity (by the parts of the host's name, any country's domain) |
| `social` | a social site's: Facebook, Instagram, X (`x.com`, `t.co`), LinkedIn, Reddit, YouTube, Pinterest, TikTok, Hacker News, Threads, Bluesky, Mastodon, VK, Weibo, Tumblr, Quora, Snapchat, Discord, Telegram, WhatsApp, Messenger, WeChat, LINE, Medium |
| `referral` | any other |

The **source** is `utm_source` where there is one (lower case), else the
referrer's host without `www.`, `m.`, `l.` in front (`l.facebook.com` is
`facebook.com`), else `(direct)`. A visit that begins inside the page (after
the gap, or past midnight), or whose landing says only direct or this site,
keeps the source of the visit before it: the last source that was not
direct, as GA4 does.

### Where people are

The country, as ISO 3166-1 alpha-2 (`DE`), from the first of these that
says one; `(unknown)` when none does. `geo=off`: none of it, and the page
does not send its time zone.

1. **A header a proxy or CDN in front writes**, where the deployment says
   which: `MOTE_GEO_HEADER=cf-ipcountry` (Cloudflare's `CF-IPCountry`),
   `x-vercel-ip-country`, `cloudfront-viewer-country` or `x-country-code`.
   It is believed only with `MOTE_PROXY` set ([the proxy in
   front](back-end.md#limits)): without one, anyone could write it, and
   the log says so once at start. `XX` and `T1` (Cloudflare's "unknown" and
   Tor) are none. With `geo=city`, `MOTE_GEO_REGION_HEADER` and
   `MOTE_GEO_CITY_HEADER` name the headers a region and a city come in
   (Cloudflare's "visitor location headers" managed transform writes
   `cf-region` and `cf-ipcity`; Vercel `x-vercel-ip-country-region` and
   `x-vercel-ip-city`, which are URL-encoded and decoded here). Any other
   name for the country's header, and the back end does not start.
2. **A file of address ranges the deployment gives**: `MOTE_GEO_DB=/path`.
   Mote downloads none. The file is text, a line a range, both ends
   included, IPv4 and IPv6 in one file:

   ```text
   start_ip,end_ip,country
   # a line that starts with # is passed over, and so is a blank one
   1.0.0.0,1.0.0.255,AU
   2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,JP
   ```

   Read whole at start into a sorted table, and asked by binary search (1.6
   µs a request with 300 000 ranges, read in 0.4 s). It is strict: a line of
   another shape, a country that is not two letters, a range that ends
   before it starts or overlaps another, and the back end does not start,
   with the line's number. Quotes around a cell are let go; the first line
   may name the three cells. Several free sources publish country files
   close to this shape (DB-IP's "IP to Country Lite" as CSV, IPtoASN's
   country files as TSV, the regional registries' delegation files):
   look at the one you take, keep the start, the end and the country, and
   write it as above (a TSV is `tr '\t' ','` away; a file of CIDR blocks
   needs each turned into its first and last address). Mind its licence.
   MaxMind's `.mmdb` files are not read: their reader is a binary tree and a
   data format of their own, which is not small.
3. **The browser's time zone**, which every browser says: `Europe/Paris` is
   France. The extension has a table of about 400 IANA zones and their
   countries (`usageZones` in `web.mote`). It is near, not exact: someone
   abroad keeps their own clock, a zone some countries share is put with
   the largest, `UTC` and the like are nowhere. The kind of answer is
   counted too (`geo`: `header`, `file`, `zone`, `unknown`).

The address is looked up at the door, in memory, and let go.

### Browsers and devices

From the User-Agent, read at the door, by a small reader in the extension
(`usageTechOf` in `web.mote`; its tests try 40 real strings): the browser
(Chrome, Safari, Firefox, Edge, Opera, Opera Mini, Samsung Internet,
Yandex, Vivaldi, UC Browser, Silk, Android WebView, Internet Explorer, and
the browsers inside other apps: Facebook, Instagram, LINE, WeChat,
Snapchat, TikTok, X, LinkedIn, Pinterest, the Google app), its major
version, the system (Windows, macOS, iOS, iPadOS, Android, ChromeOS,
Linux), and the device: `desktop`, `tablet`, `phone` or `bot`. Where the
browser gives its own name (User-Agent Client Hints: Chromium's
`navigator.userAgentData`, or the `Sec-CH-UA` headers), that is believed
over the User-Agent: Brave and Edge say who they are there. (An iPad that
asks for the desktop site says it is a Mac, and is counted as one.) The
screen's width and the window's are counted in five buckets (`< 576`,
`576–767`, `768–991`, `992–1199`, `≥ 1200`), the pixel ratio in four, the
language as the browser says it (`en-US`).

### Bots

A crawler, a monitor or a script is not a person, and nothing of it is
counted: an empty User-Agent, one that says it is a bot, a spider, a
crawler, a monitor, a preview, a script's library (`curl`, `python`,
`okhttp` …), `HeadlessChrome`, or a browser that says a program drives it
(`navigator.webdriver`). `USAGE_BOTS=keep` keeps them, as the device
`bot`. A browser a test drives is such a browser, so a test that counts
itself says `USAGE_AUTOMATION=count`: it counts those that say
`navigator.webdriver` and `HeadlessChrome`, and still leaves out the rest.
(The runs in `tests/` say it; a deployment should not.)

### Speed

One page load in `vitals` (10) measures how fast it was, with what the
browser itself measures (`PerformanceObserver`; nothing is made up where it
does not): **LCP** (the largest paint), **CLS** (the largest burst of
layout shifts no input caused), **INP** (the slowest interaction), **TTFB**
(when the first byte of the page came). It is sent once, as the page is
first hidden, as the route it loaded on. The panel shows, for each route,
the value 75 in 100 of the loads measured came in under (the p75 Google's
Core Web Vitals are read at), coloured good, needing work, or poor by
web.dev's thresholds (LCP 2.5 s / 4 s, INP 200 / 500 ms, CLS 0.1 / 0.25,
TTFB 0.8 / 1.8 s). It is read from a histogram of 20 steps, so 1 300 means
"between 1 000 and 1 300 ms".

### Now

`usageNow()` and `UsageNow`: who is here now, as the pages' [open
lines](#the-open-line) say: the people with a tab open, how many tabs, how many
are looking (a tab shown), and the screens they are on. Where no line has said
anything for five minutes, the people who did something in the last five
minutes, and the screen each is on (`UsageLive`, a row a person): then someone
reading one page for six minutes without doing anything has gone from it. It is
read from what has been kept, so it is a handing over (five seconds) late;
`UsageNow` asks again every 15 seconds.

### The open line

A page with usage on keeps the open line to its back end (`/live`, the one `live` values and
events ride: [back-end.md](back-end.md)), whether or not it keeps a `live` value; a page with
usage off has none of it, and opens none. (A browser that asks not to be tracked opens none for
usage either, unless `dnt=ignore`: its page notes nothing.) On it:

- **What the page saw** goes every three seconds while there is anything, as
  `{t: "ug", b: {s, u, c, e}}`: the same batch the door below takes. With no line open (it is
  being opened again, or cannot be), it is posted to the door instead, every 15 seconds; as the
  page is hidden or closed, it is handed to the browser to send (`sendBeacon`), since a line may
  not live long enough to carry it. With `usage="signed in"` it is always posted: the answer says
  whether anyone is counted.
- **That the tab is here**: as the line opens (and opens again), as the route in front changes,
  as the page is shown or hidden, and every 15 seconds, the page says `{t: "uh", s, u, c, r, x, v}`
  (its session, its visitor's id, what the browser is, the route and the address in front,
  whether it is shown). The back end makes of it the events `here` (the first time, when the
  route or whether it is shown changes, and every 30 seconds) and `gone` (when the tab's last
  line has been closed for `MOTE_USAGE_GRACE`, 30 seconds, with no line of it open again). So a
  line that drops and opens again is the same tab, not a new visit; two tabs of one browser are
  one person with two tabs (each tab has a session of its own, `mote_usage` in
  `sessionStorage`); a reload is the same tab.
- **Who**: the line's own session, as every call's. The headers of the request that opened the
  line are read as a call's are (what the browser is, Do Not Track, Global Privacy Control),
  never its cookie; its address is looked up as the door does and let go.
- **Several back ends**: each tells what its own lines said. A tab whose line moves to another
  back end is `here` there; the `gone` the first one says later is older than that, and is let go.
  A back end that stops says no `gone` for its lines: a tab whose line has said nothing for a
  minute is not here, gone or not.
- **Limits**: what rides the line is held to what the door holds a page to (below), and to the
  line's own (`MOTE_LIVE_RATE`, `MOTE_LIVE_MESSAGE`); a tab's first word counts against what its
  sender may send in a minute; past what the back end holds between handings over, events are
  dropped and counted, as the door's are. A batch sent on a line that then drops is lost, as a
  post that gets no answer is.

The extension keeps each tab in `UsageHere` (one row a tab: who, the route, whether it is
shown, since when, when its line last spoke, gone and how long it was here) and `usageNow` reads
it: **exact** where the lines have said anything in the last five minutes (a tab is here when its
line spoke in the last minute and it is not gone), the five-minute guess below where they have
not (a back end of an older build, say). `here` and `gone` are not things done: they are in no
count, no visit and no funnel.

### Autocapture

With `autocapture=on`, the page also notes, with no line written for them:

- **A press on a control** (`click`): a button, a link, a field, a `summary`, a `label`, anything
  with a role of a control, anything with a `data-mote` name. It is named by its `data-mote`
  name, which is the action it runs or the state it sets (every control has one: [agents.md](agents.md)),
  else a field's `name`, else its tag. Its words are not sent: a button's label can be a name.
- **A field changed** (`change`): as the browser says it changed (a field left after typing, a
  choice made), by its name and its type (`email`, `checkbox`). **Never what it holds.**
- **A rage click** (`rage`): three presses or more within a second, within 30 pixels of each
  other, said once a burst. Where the presses were is looked at in the page, in memory, and is
  never sent.
- **A dead click** (`dead`): a press on a button, a link, a `summary` or anything with the role of
  one, after which nothing on the page changed (nothing added, taken away or changed, no scroll,
  no change of selection or address) for a second and a half. A press that leaves the page is not
  dead. A press whose answer takes longer than that is said to be, so read them as worth a look.
- **Inside an element that says `private` or `data-private`**, a control is named `private`.

They are counted as actions are (`UsageTop kind="click"`, `"change"`, `"rage"`, `"dead"`: how
many times each control was pressed, which is as far as a heatmap goes here: no positions are
kept), and a funnel's step may be a control's name.

### Goals

A goal is a `track` name or a route (`/thanks`, the pattern or the address)
that counts as a visit reaching what the site is for:

```text
fn usageGoals(): string[] = ["checkout", "signup done", "/thanks"]
```

(`wants fn usageGoals(): string[] = []`: the extension's, which a program
may replace; `USAGE_GOALS="checkout,/thanks"` adds to it.) A goal counts
once a visit, and a visit's first goal is its **conversion**. The panel
shows each goal's conversions and their share of visits, and one goal by the
visits' source, class, campaign, country or device: of the visits with each,
how many reached it. A goal reached makes the visit no bounce.
## track

```mote
// docs: whole
app "Shop" usage=on

shape Cart
  plan: string
  total: number

state cart: Cart = {plan: "pro", total: 40}
state seen = 0

server fn pay(plan: string, total: number): number
  // On the back end too: as whoever made the call.
  if total > 1000 track("large order", {plan})
  return total

// A consumer of one's own: every batch, counted. (The extension is one of these.)
model Tally
  name: string key
  count: int = 0

server on usage(batch)
  for e in batch
    let name = `${e.kind} ${e.name}`
    let row = Tally.get(name)?
    if row == none
      Tally.add({name, count: 1})?
    else
      Tally.set(name, {count: row.count + 1})?

server fn tallied(): number
  return Tally.count({})?

action checkout
  pay(cart.plan, cart.total)?
  track("checkout", {plan: cart.plan, total: cart.total, gift: false})
  seen = tallied()?

button "Check out" press=checkout
text `${seen}`
```

- **`track(name)`** or **`track(name, props)`**, in an action, a handler, a
  `server fn`, a hook, a job. It gives nothing and cannot fail.
- **A name** is a letter, then letters, digits, spaces and `_ . - :`, 64 at
  most. Written out, it is checked when compiled (`H153`); worked out, when
  it runs (one that does not fit is dropped).
- **Properties** are a flat record of texts, numbers and yes-or-nos, 12 at
  most (`H153` for a list, a record inside, a thirteenth). A text is cut to
  200 letters. They are what the numbers are later broken down by, so say
  what will be asked about: `plan`, not the cart.
- **With usage off it is nothing**: the line compiles to nothing, and its
  arguments are not worked out. So it can stay in a program whatever the
  `app` line says.
- A program's own `fn track` or `action track` is its own: the word is
  taken only where nothing declares it.

## The panel

`use "pkg:usage/usage.mote"` gives these components. Each needs nothing
said, follows the app's colours in light and dark, and wraps at a phone's
width.

| | |
|---|---|
| `UsagePanel` | Everything below but the chart and the funnel, with a choice of today, 7, 30 or 90 days. `last="14 days"` fixes the span. `app="planner"`: one app's, where the program keeps several ([below](#several-apps-one-panel)); it may change while the panel is shown. |
| `UsageOverview last="30 days"` | Visitors, visits, pageviews, pages a visit, the bounce rate and the time in front a visit, each against the span before it (▲ 12% on the span before); visitors and pageviews day by day. |
| `UsageNow` | People here in the last five minutes, and the screens they are on; it asks again every 15 seconds. |
| `UsagePages last="30 days" limit=10` | The pages most viewed: views, entrances, exits, time in front a view, and each page's title. |
| `UsageSources last="30 days" limit=8` | Where visits came from, by source, class, referrer, campaign, medium, term or content (a choice): visits, the share that bounced, the share that converted. |
| `UsageCountries last="30 days"` | Countries, with their flags (the system's emoji, from the code), and with `geo=city` regions and cities, and how each country was known. |
| `UsageDevices last="30 days"` | Devices, browsers, browser versions, systems, screen and window widths, pixel ratios, languages, new and returning. |
| `UsageGoals last="30 days"` | Each goal: how many visits reached it, their share of visits; and one goal by source, class, campaign, country or device. |
| `UsageVitals last="30 days" limit=10` | Each route: LCP, INP, CLS and TTFB as 75 in 100 measured loads came in under, coloured good, needing work or poor. |
| `UsagePeople last="30 days"` | Active today, this week (from Monday), this month; each day's people, returning and new. |
| `UsageTop kind="screen" last="30 days" limit=8` | The most used of a kind: `screen`, `action`, `call`, `track`, `job`, `failure`, `signin`, `signup`. How often; the share that failed; for actions, calls and jobs the time half of the runs, and 95 in 100, came in under. |
| `UsageChart event="checkout" by="plan" last="30 days"` | A `track` event day by day; with `by`, split by one property's values (the four most seen, and the rest together). A number is summed, and shown with its average. |
| `UsageFunnel steps=["signup", "/cart", "checkout"] last="30 days" within=24` | How many people got how far, in order. A step is the name of anything a person does: a route, an action, a `track` event, `signin`, `signup`. `within`: hours from the first step. |
| `UsageRetention weeks=8` | Of the people first seen in each week, the share seen again in each week after. |

With the [admin extension](admin.md), `use "pkg:admin/usage.mote"` puts
`UsagePanel` in the admin panel as a tab, and says `usageMay` as "whoever
the rule `admin` admits".

A span is `"today"`, `"30 days"`, `"2 weeks"`, `"3 months"`. (It is `last=`, not
`over=`: on a component `over=` is [an event](events.md).) Every component
takes `app=` as well ([below](#several-apps-one-panel)).

### Who may read it

**The program says, and until it does it does not compile**: the extension
says `wants fn usageMay(): bool`, and a program that does not declare it is
told so at its entry (`H166`: `the program must declare fn usageMay(): bool
for pkg:usage`, with the line to write).

```text
fn usageMay(): bool
  let me = auth.me()?
  return Staff.has({who: me?.id ?? "", admin: true})?
```

- Every question is a `server fn … requires signedIn` that asks
  `usageMay()` before it reads anything; anyone else is told `Usage is not
  yours to read.` (kind `refused`), and the panel shows that line.
- The models have no rules, so no page can reach them: `POST
  /rpc/UsageRaw.find` is `no such call`, for the admin too.
- `usageMay` is the back end's fn, called as whoever made the call. If it
  fails, the answer is no. (One that cannot fail, `fn usageMay(): bool =
  true`, is as good.)
- [`mote check --access`](back-end.md#who-may-do-what) lists the
  questions, the models (each "closed to the page") and the runtime's door
  (`usage.send`).

## The questions

The panel is made of these, and a page of the program's own may call them.
All are `server fn`s of the extension, guarded as above; `days` is 1 to 366.

| | Gives |
|---|---|
| `usagePeople(days, app?)` | `{today, fresh, week, month, days: [{day, label, active, fresh, returning}]}` |
| `usageTop(kind, days, limit, app?)` | `[{name, count, failed, rate, p50, p95, share}]`, the most used first |
| `usageSeries(kind, name, days, app?)` | `[{day, label, count, failed}]`, a row for each day |
| `usageBreakdown(event, prop, days, app?)` | `{values: [{value, count, sum}], days}`; `days` are rows for a chart, a field for each value |
| `usageFunnel(steps, days, hours, app?)` | `[{step, people, rate}]` |
| `usageRetention(weeks, app?)` | `[{week, people, after: [1, 0.5, …]}]` |
| `usageOverview(days, app?)` | `{shown, before, days}`: `shown` and `before` (the as many days before) are `{visitors, sessions, pageviews, pagesPer, bounceRate, engaged, conversions, conversionRate}`; `days` are `[{day, label, visitors, sessions, pageviews}]` |
| `usageDims(dim, days, limit, app?)` | `[{value, label, visitors, sessions, pageviews, bounceRate, engaged, entrances, exits, conversions, rate, share}]`, most visits first (for `"page"`: most views, `label` its title, `engaged` the time in front a view); `visitors`: each day's different visitors of the value, added up over the days |
| `usageNow(app?)` | `{people, pages: [{page, people}], exact, tabs, looking}`: `exact` where the open lines say who is here |
| `usageGoalsSeen(days, app?)` | `[{goal, conversions, rate}]` |
| `usageGoalBy(goal, dim, days, limit, app?)` | rows as `usageDims`: of the visits with each value, how many reached the goal (`rate`) |
| `usageVitalsSeen(days, limit, app?)` | `[{route, samples, lcp, cls, inp, ttfb}]`, p75 each (milliseconds; CLS as it is), -1 where none was measured |

A dimension (`dim`) is one of `page`, `class`, `source`, `referrer`,
`campaign`, `medium`, `term`, `content`, `country`, `region`, `city`,
`geo`, `browser`, `version`, `os`, `device`, `screen`, `viewport`, `dpr`,
`language`, `visitor`, `goal`; a visitor is counted in a span once however
many days they came (up to 10 000 different people; past that the number
says 10 000). `app`, left out, is the program's own (`""`).

### A visitor who signs in

Someone who looks around signed out and then signs up or in is one person,
not two. The sign-in or sign-up says the id the browser had until then
(`anon`, beside `user`), and the extension joins them: what the visitor did
is the account's (a funnel from the landing page through `signup` is one
person's), the days they were seen are the account's (a day, a week or a
month both were seen in counts one person), the account was first seen when
the visitor was, and the visit they are in goes on as the account's (no
second visit, no second visitor). Nothing new is kept to do it: no address,
no email; the id is the visitor's random one, and it goes with the rest.

### Several apps, one panel

One program may keep the numbers of several: a site and its app, say, on
one admin page. Each of the others gathers what its visitors do
(`usage=on`) and keeps none of it: its `server on usage` passes each batch,
as it is, over a [signed call](back-end.md#another-back-end) to the one
that keeps them, which says whose it is. The keeper takes the extension and
does **not** say `usage=on` itself, so its own admin pages are not counted.

```text
// The site and the planner (each with USAGE_APP=site or planner, and USAGE_TO).
app "Planner" usage=on

extern server fn usageFrom(app: string, batch: json): bool at env("USAGE_TO")

server on usage(batch)
  usageFrom(env("USAGE_APP"), batch)?
```

```text
// The keeper: the extension, and no usage=on.
app "Admin"
use "pkg:usage/usage.mote"

server fn usageFrom(app: string, batch: json): bool requires peer
  if !["site", "planner"].includes(app) fail("no such app")?
  let events: UsageEvent[] = batch ?? []
  usageTake(events, app)?
  return true

// Each app's goals (unsaid: usageGoals() for every one).
fn usageGoalsFor(app: string): string[] = app == "planner" ? ["checkout"] : ["/pricing"]

state which = "site"

route "/usage"
  Select value=which options=["site", "planner"]
  UsagePanel app=which
```

- **`usageTake(batch, app)`** keeps every row under `app` (a short name:
  letters, digits, `_ . : -`), and a row's key that is a slug has the app
  before it (`@planner|2026-11-21|screen|/`), so two apps' counts never
  meet. `usageTake(batch)` is the app `""`, the program's own: what
  `server on usage` does, and what every program did before there were
  apps, with the keys it always had.
- **Every question takes `app` last, and every component `app=`**; left
  out, `""`. A visitor who signs up in one app is joined in that app only.
- The night's prune goes through each app.

## What is kept, and for how long

All in the models' database (`app.sqlite`), in eleven models of the extension.
Every row says its `app` (`""`, the program's own, unless
[said](#several-apps-one-panel)); a database made before there were apps
has every row in `""`, as the next start's schema step gives them:

| Model | A row for | Kept |
|---|---|---|
| `UsageCount` | each name, each day: how often, how often failed, a small histogram of how long | for good |
| `UsageProp` | each value of each property of a `track` event, each day (20 values a day for a property, then `(other)`; a number is one row with its sum) | for good |
| `UsageActive` | each day, week and month: how many different people | for good |
| `UsageRaw` | each thing a person did (not calls, jobs or leaving a screen: those are only counted) | `USAGE_KEEP_DAYS`, 90 unless set |
| `UsageSeen` | each person, each day they were seen | the same |
| `UsagePerson` | each person: when first and last seen | until not seen for that long |
| `UsageDim` | each value of each dimension, each day: visitors (each different one once a day), visits, pageviews, bounces, time in front, entrances, exits, conversions (200 pages a day, 250 countries, 100 regions and cities, 50 of the others, then `(other)`; an address and a title are cut to 200 and 80 letters) | for good |
| `UsageVital` | each route, each metric, each day: how many loads were measured, and a histogram of 20 steps | for good |
| `UsageVisitor` | each visitor, each day they came | `USAGE_KEEP_DAYS` |
| `UsageLive` | each person: the visit they are in, or were last in (its values, its pages, the page in front, the values they were counted a visitor of today) | two days after it ends |
| `UsageHere` | each tab whose [open line](#the-open-line) said it is here: who, the route, whether it is shown, since when, when its line last spoke, gone and how long it was here | two days after its line last spoke |

- **A batch is kept in one turn** (`atomic`): all of it, or none.
- **A night's prune** (`server at "03:10"`) removes what is older than
  `USAGE_KEEP_DAYS`. Counts stay, so the charts go back as far as the
  program does; funnels and retention reach back as far as the days kept.
- **A day** is a day in `USAGE_ZONE` (`UTC` unless set, e.g.
  `Europe/Paris`); a week starts on Monday.
- **A person** is an account's id, or a visitor's random id. Someone who
  browses signed out and then signs in is one: the visitor is joined to the
  account ([above](#a-visitor-who-signs-in)). Someone not seen
  for `USAGE_KEEP_DAYS` is forgotten, and is new if they come back.
- **Times are read from a histogram**: a median of `500` means "under half
  a second", one of eleven steps from 10 ms to 30 s.
- **To forget a person**: `UsageRaw.del({who: id})`, `UsageSeen.del({who:
  id})`, `UsagePerson.del(id)`, `UsageVisitor.del({who: id})`,
  `UsageLive.del(id)`, `UsageHere.del({who: id})` in a `server fn` of the program's. The counts hold no
  ids.

**Rows a day, before and after the web's numbers**, for a plausible site:
1 000 visits a day by 800 visitors, three pageviews a visit, 50 pages seen
a day, 20 sources, 10 campaigns, 40 countries, 3 goals, 20 routes measured.
Before: about 70 rows of counts and 200 of people a day for good, and a row
for each thing a person did for 90 days. After, as well: about 400 rows of
`UsageDim` and 80 of `UsageVital` a day for good (at most about 3 500 and
80 a route, whatever happens: the caps), 800 of `UsageVisitor` for 90 days
(72 000), and a row a visitor in `UsageLive` (about 1 600). Pageviews and
leaving add no rows of events: a screen was kept one by one already, and
leaving is counted only.

## The seam

For a consumer of one's own, or a second one beside the extension (every
block is told, in the order written).

```text
server on usage(batch)        batch: UsageEvent[]
  for e in batch
    …
```

| Field | |
|---|---|
| `name` `kind` | as [above](#what-is-gathered) |
| `at` | when, in milliseconds. For a page's event: the back end's clock when it arrived, less how long ago the page said it was (an hour at most) |
| `user` | the id of who was signed in, or none |
| `anon` | a visitor's id, where nobody was signed in and the page made one; on a `signin` or `signup`, beside `user`, the id the browser had until then (none where it had none) |
| `session` | the tab's id, for a page's event; `""` for the back end's own |
| `route` | the route it happened on, for a page's event |
| `ms` `ok` `failKind` | how long, whether it went well, and the failure's [kind](back-end.md#when-something-fails) if not |
| `props` | what `track` was given, cleaned (`json`); for a `vital`, `{lcp, cls, inp, ttfb}` |
| `path` | for a screen and its leaving: the address, with its ids as names unless `paths=full` |
| `title` | for a screen: the page's title then |
| `referrer` | for the first screen of a page's loading: the other site's host, `"self"` for this one's, `""` for none; none on a screen shown inside the page |
| `utm` | for that screen: `{source, medium, campaign, term, content}` (each a text or none), or none |
| `client` | for a page's event (`UsageClient`): `{ua, brands, mobile, platform, lang, zone, screen, viewport, dpr, webdriver, country, region, city, geoFrom}`: the User-Agent and the browser's own name for itself, its language and time zone (`""` with `geo=off`), the screen's and the window's widths, the pixel ratio, whether a program drives it, and where it is as a proxy's header or the file of addresses says (`geoFrom`: `"header"`, `"file"`, `""`; `"off"` with `geo=off`). Never the address. |

- **When.** Every five seconds while there is anything (`MOTE_USAGE_MS`),
  and once more as the back end [stops](back-end.md#health-and-stopping),
  after its calls and jobs have finished and before `server stop` blocks
  run. Nobody is signed in in the block. With several back ends at one
  database, each hands over what it saw.
- **A block that fails** is logged like a `server every` block's failure
  (`where: "every"`, `block: "server on usage"`), `server on failure` hears
  a fault, and the next block is still told. The batch is not handed over
  again: usage may lose a few seconds, and never holds anything up.
- **Limits**, all dropping and never refusing: a page keeps 200 events at
  most between sendings, 30 of one name; the back end takes 100 events a
  request, 300 a minute from one person, and for people who are signed
  out 1500 a minute from one address (`MOTE_USAGE_ADDRESS`; the address is
  the caller's as a [`limit`](back-end.md#limits) knows it, so set
  `MOTE_PROXY` behind a proxy) and 3000 a minute from all of them together
  (`MOTE_USAGE_ANON`); it holds 50000 between two handings over
  (`MOTE_USAGE_HELD`). The minute is the back end's one clock's. What it dropped is a line of the log at `warn`
  (`msg: "usage"`, `dropped`).
- **The door** is `POST /rpc/usage.send`: a page posts what it saw every 15
  seconds while there is anything and no [open line](#the-open-line) to send it on,
  and as it is hidden or closed. It is a
  door of the runtime's own, and stands in [the order every call's door
  does](back-end.md#rules): where the request came from is asked whenever it
  says (a page of another site is refused, `403`, signed in or not); no
  answer of it is [remembered under an id](back-end.md#a-call-is-answered-once),
  and a page sends a batch once and never again (one that is lost is lost;
  one sent twice by something else is counted twice); its line in the
  [log](back-end.md#logs) is at `debug`. It is not among the calls of
  `api.json`, which says `"usage": "on"` (or `"signed in"`) where usage is
  gathered. With usage off there is no such call (404).
- **Nothing is counted of someone [acting as
  another](back-end.md#acting-as-someone)**: their page notes nothing and
  sends nothing while it knows, and the back end, which goes by the session,
  takes no batch from it, tells no call made on it, and passes over a
  `track` on its behalf. The call that began the acting is the caller's own.
- **A model's write a page [shows at once](models.md#a-write-shows-at-once)**
  is one `call` event when the back end has made it (or refused it: `ok` is
  false), however many times the page had to send it. The action that made
  it is told when the action itself ends, which is at once: a refusal that
  arrives later is the call's failure, and a `failure` event for the page
  only where nothing in the page heard it.
- **In a test** ([testing.md](testing.md)) no timer runs: what was gathered
  is handed over whenever the test moves its clock (`clock +1 second`),
  before anything else the move runs.

```mote
// docs: whole
app "Shop" usage=on geo=city paths=full vitals=all

// A consumer of one's own: screens by where, campaign and address, as each page's browser said them.
model Seen
  key: string key
  count: int = 0

fn where(c: UsageClient): string = c.city ?? c.country ?? (c.zone == "" ? "(unknown)" : c.zone)

server on usage(batch)
  for e in batch
    let c = e.client
    if c == none || e.kind != "screen" continue
    let campaign = e.utm?.campaign ?? "(none)"
    Seen.put({key: `${where(c)} ${campaign} ${e.path ?? e.name}`, count: 1}, {count: inc(1)})?

route "/"
  text "Home"
route "/job/:id"
  text `Job ${id}`
```

`extensions/usage-forward` is the smallest consumer: it posts each batch to
an address (`USAGE_FORWARD_URL`), for a team that keeps its numbers in
another tool; what it posts has each page's `client` too, the User-Agent
with it (never an address). Both extensions can be taken at once.

## What it costs

Measured on the run `tests/e2_usage` (one laptop, November 2026):

- **The open line and autocapture** (the run `tests/e2c_live`, November 2026): the page of
  `tests/e2_usage` is 2.3 KB larger (0.8 KB gzipped: the line, which a page that keeps no
  `live` value now carries, and autocapture's code, which is there whether it is said or not),
  the back end 7.1 KB (the line's part). On the wire: a tab's word that it is here every 15
  seconds (a few hundred bytes, with what the browser is), and what it saw every three seconds while
  there is anything, on a line already open: no request, no headers, no cookie each time.
- **The page**: 5.7 KB of JavaScript more (2.3 KB gzipped): 4.8 KB for the
  part (it was 1.9 KB before the web's numbers: the address, where a visit
  came from, the time in front, what the browser is, the speed), the rest
  about 24 bytes an action and a route. The back end's module: 10.7 KB more
  (4.3 KB before). The extension's panel and questions, in a program that
  takes it: 23 KB more page than before (5 KB gzipped), 38 KB more back end.
  Nothing when usage is off: five programs without it (`tests/pages/notes`,
  `feed`, `atlas`, `tests/engine_scale`, `examples/slick`) build byte for
  byte as they did before, page and back end.
- **At the door**, once a request: what the browser is, 1.2 µs; with a
  country from a proxy's header, the same; from a file of 300 000 ranges
  (binary search), 1.6 µs for an IPv4 address and 2.9 µs for an IPv6 one.
  The file is read at start (10.6 MB in 0.4 s).
- **Keeping it** (the extension, in its turn of the database): about 120 µs
  an event of a page, against 57 µs before (batches of 100 screens and
  leavings of 200 people), most of it the visits' rows; reading a
  User-Agent is 4 µs of that, once a browser a batch.
- **A call**: 52.6 µs against 51.5 µs for the same call over HTTP on one
  machine (the median of eight rounds of 5000 each way): about a
  microsecond, which is inside what the rounds differ by.
- **The wire**: one request every 15 seconds from a page that is being used,
  none from one that is not, one more as it is hidden. A pageview (its
  screen and its leaving) is about 160 bytes (110 before: the address and
  the title are new); a batch about 160 (90 before: what the browser is; 80
  more where it gives its Client Hints); a landing 55 more (where it came
  from, the campaign); a measured load 70, once.
- **The database**: a row for each name each day (`UsageCount`), a row for
  each person each day, and a row for each thing a person did, calls not
  among them, for 90 days. A program with 40 screens and actions, 30 calls,
  200 people a day who each do 50 things: about 70 rows of counts and 200
  of people a day for good, and 10000 rows of events a day, 900000 at any
  time (around 150 MB), which `USAGE_KEEP_DAYS` sets.

Recorded: `tests/expect/real_e2_usage.txt` (a browser, a second one signed
out, what a page cannot read, forge or flood, a browser that asks not to be
tracked, the panel in light, dark and at a phone's width, `usage="signed
in"`, and no usage at all), `real_e2_rollup.txt` (the extension's own
tests, by the clock: the UA reader's 40 strings, sources, zones, visits and
bounces, goals, caps, speed, bots) and `real_e2b_web.txt` (browsers with
other User-Agents, languages, time zones, screens, referrers and campaigns;
a proxy's country, region and city; a file of ranges and its edges, IPv4
and IPv6; the header not believed without `MOTE_PROXY`; `geo=off`; a
crawler; Global Privacy Control; a browser a program drives; the panel's
numbers; no address in the databases or the logs; a file of ranges that is
wrong, and the back end not starting) and `real_e2c_live.txt` (what a page saw
going over the open line, none of it posted; two tabs of one browser, one
person; a line dropped and opened again, the same tab; a line cut for good, and
what the page saw posted instead; a tab closed, gone; who is here now, exact;
presses, a field changed, a rage click, a dead click, a control inside
`private`; a browser that asks not to be tracked, with no line; a page with no
usage, with none).

Settings of the extension: `USAGE_KEEP_DAYS` (90), `USAGE_ZONE` (`UTC`),
`USAGE_SESSION_MINUTES` (30), `USAGE_GOALS`, `USAGE_BOTS` (`keep`),
`USAGE_AUTOMATION` (`count`, for tests). Of the runtime: `MOTE_GEO_HEADER`,
`MOTE_GEO_REGION_HEADER`, `MOTE_GEO_CITY_HEADER`, `MOTE_GEO_DB`, and the
`MOTE_USAGE_*` above, with `MOTE_USAGE_GRACE` (30000: how long a tab's line may
stay closed before the tab is gone).

Source: `compiler/src/usage.rs`, `runtime/page/usage.mote`,
`runtime/server/usage.mote`, `extensions/usage/` (`visits.mote` and
`web.mote` for the web's numbers).
