# The UI

> The web UI at /ui/, covering setup, password and GitHub sign-in, roles, each screen, editing settings, and its security and operations.

Web page: https://visto-ai.com/docs/the-ui/

Visto AI can serve a web UI at `/ui/`. It shows what the service is doing and has done: reviews with their scores and findings, automatic approvals, alerts and the health of each dependency, how well the score works on each repository, and what the service learned from people. Admins also edit most settings there and keep the accounts. People sign in with a password account of the service's own, or through the GitHub App.

## Set it up

### Turn it on

The UI is on when the config writes `ui.publicUrl`, the address people open the service at:

```yaml
ui:
  publicUrl: https://visto.example.test
```

`ui.publicUrl` is an `https` address with no path, query or user name; `http://localhost` and `http://127.0.0.1`, with or without a port, are accepted for a try on one machine. With `ui.publicUrl` alone, password sign-in is the only way in and no client id or secret is needed. With no `ui` block, or one that writes none of `publicUrl`, `accounts`, `team` and `openSignIn: true`, the UI is off and `/`, `/ui/` and `/api/` answer 404 `not_found`.

**A new database has no account**, so nobody can sign in until you make the first admin.

### Make the first admin

Run the accounts command where the service runs, with its config. Under Docker:

```bash
docker compose exec app npm run accounts -- make --config /config/config.yml --name <name> --role admin
```

It prints a one-time password once. Within 72 hours, open `<ui.publicUrl>/ui/signin`, sign in with the name and that password, and choose your own. Admins then make further accounts in Settings. If every admin loses their password, `reset` an admin with the same command (see [The accounts command](#the-accounts-command)).

### Add sign-in through GitHub

Sign-in through GitHub runs beside password sign-in. Turn it on by naming who may use it:

```yaml
app:
  clientId: Iv1.0123456789abcdef
  clientSecret: { env: APP_CLIENT_SECRET }
ui:
  publicUrl: https://visto.example.test
  accounts: [octo-lead]               # GitHub logins, at most 100
  team: [acme/backend, acme/frontend] # one <org>/<team-slug>, or a list of 1 to 10
```

With `ui.accounts`, `ui.team` or `ui.openSignIn: true` written, `ui.publicUrl`, `app.clientId` and `app.clientSecret` must be written too, or the start (and the eval commands) refuse the file with `<key>: must be written when ui names accounts or a team, or opens sign-in`. A written `clientSecret` is always read, so its variable must be set. Who may sign in through GitHub comes from the file only; password accounts and roles live in the database.

On the app's settings page on GitHub (see [Creating the app](https://visto-ai.com/docs/create-the-github-app/)):

1. Set the **Callback URL** to `<ui.publicUrl>/api/auth/callback`, and keep "Expire user authorization tokens" on.
2. Generate a **client secret** into the variable `app.clientSecret` names, and copy the **Client ID** into `app.clientId`.
3. With `ui.team`, install the app on each organisation it names and accept the organisation permission **Members** read. Without it, each start logs and raises `feature_off` (feature `ui`, `members:read`) and keeps running, and sign-in through a team is refused.

New GitHub accounts start as viewers. To make a login an admin, before or after its first sign-in:

```bash
docker compose exec app npm run accounts -- github --config /config/config.yml --login <login> --role admin
```

### Open sign-in to anyone, for a public demo

```yaml
ui:
  publicUrl: https://demo.example.test
  accounts: [octo-lead]   # your own login, to stay an admin
  openSignIn: true
```

With `ui.openSignIn: true`, anyone with a GitHub user account may sign in, as a viewer: they see every screen a viewer sees, for every repository the service has stored.

**It needs a second, public GitHub App for sign-in.** GitHub lets only members of the owning organisation authorise a private app, and the reviewing app must stay private, or anyone could install it on their own repositories and have them reviewed on your model and shown here. So create a second app on GitHub (Settings, Developer settings, GitHub Apps, New GitHub App) that does nothing but sign people in:

1. Any name, homepage `<ui.publicUrl>`, **Callback URL** `<ui.publicUrl>/api/auth/callback`, "Expire user authorization tokens" on.
2. **Webhook**: Active off. **Permissions**: none. **Where can this GitHub App be installed?**: Any account.
3. Generate a client secret. Write that app's **Client ID** as `app.clientId` and its secret in the variable `app.clientSecret` names. The reviewing app's `app.id`, private key and webhook secret stay as they are.

The sign-in only exchanges the code with the client id and secret and reads `GET /user` once; team membership is still read through the reviewing app. Anyone may install the sign-in app too: with no permission and no webhook, an installation gives it nothing.

Three rules come with open sign-in:

- **Always a viewer.** A person let in only because sign-in is open is a viewer whatever their account's role says, so an admin cannot make them one in Settings. To be an admin through GitHub, a login must be in `ui.accounts` or a team.
- **Public repositories only.** While the key is on, the service ignores every event of a repository GitHub does not mark public (the delivery is recorded as ignored with the reason `private_repository`), so no private code or comment is ever stored. What the database held before the key was turned on stays visible: turn it on only on a deployment that has never reviewed a private repository. A review already queued when a repository turns private still runs, and what is stored stays visible. `npm run eval:seed-memory` refuses a config with the key on, since a history file can come from a private repository.
- **The account cap.** With 1,000 accounts, a new person's sign-in removes the viewer account a sign-in made whose last sign-in is the oldest, if that is at least 30 days ago (recorded as `removed` by `sign_in`). It never removes the account of a login in `ui.accounts`. With none that old, it is refused as `full`. Only a GitHub sign-in frees an account: one made in Settings or by the command is refused as `full` as before, so when the cap is near, remove viewers in Settings to make room. Accounts made through open sign-in stay after the key is turned off; remove them in Settings.
- **One session an account.** A sign-in through open sign-in ends that account's other sessions.

### Serve it at its own address over HTTPS

The UI's cookies are `Secure`, so serve it over HTTPS (browsers keep `Secure` cookies on `http://localhost`). Open it at `ui.publicUrl` exactly: a password sign-in from another name for the host (`127.0.0.1` while `ui.publicUrl` says `localhost`), or through a proxy that rewrites `Origin`, is refused as `origin`, and a GitHub sign-in started at another name loses its state cookie (`state`).

### Run it outside Docker

The Docker image builds `ui/` in its own stage. Outside Docker, build the files first (the install reaches the network):

```bash
npm --prefix ui ci && npm --prefix ui run build
```

The service reads `ui/dist` once, at start, and serves it from memory, so restart it after a rebuild. With nothing built, `/ui/` answers 404 while the API works, and the start logs `{ event: 'ui', files: 0 }`.

## Sign in with a password

The sign-in page has a name, a password and **Sign in**, and **Sign in with GitHub** while that is on. With `ui.openSignIn`, **Sign in with GitHub** comes first, under a line saying that anyone with a GitHub account can sign in as a viewer, and the name and password follow. The name is trimmed and lower-cased before lookup.

### One-time passwords

An account made or reset gets a one-time password: 20 characters from `23456789abcdefghjkmnpqrstuvwxyz` (about 99 bits), shown once to whoever made it, stored only as a hash, valid for 72 hours.

A right one-time password does not sign you in by itself. The page turns into **Choose your password**: type a new password twice, then **Choose and sign in** (or **Cancel**). The service checks the one-time password again before setting yours; a reset made meanwhile wins. An expired one-time password reads "This one-time password has expired. Ask an admin for a new one.", but only after the right one was typed, so it tells nothing to someone who does not hold it.

### Password rules

- 12 to 128 characters, counted as code points and not normalised: a password typed in another Unicode form does not match.
- A new password must be well formed (no lone surrogate), hold no NUL character, and differ from the one-time password.
- Stored only as an scrypt hash (N = 2^15, r = 8, p = 1, 16-byte salt, 32-byte key, written `scrypt$15$8$1$<salt>$<key>`) and compared in constant time. A stored value of another form, or one naming a higher cost, verifies nothing.

### Wrong passwords and the wait

After 5 wrong passwords in a row, an account waits 15 minutes by the service's clock, during which no password is checked against it, the right one included. A right password, a reset, or a change of one's own password clears the count. Someone who knows a name can keep that account waiting; an admin's reset ends it. Nothing limits requests by address or rate: put that in the proxy in front.

Every refusal reads the same. A wrong password, an unknown name, a GitHub login typed as a name and a waiting account are all 401 `refused`: "The name or the password is wrong. After five wrong tries in a row, an account waits 15 minutes." Each costs exactly one verify, against the account's hash or a dummy hash made at start, so timing does not tell names apart.

## Sign in through GitHub

1. **Sign in with GitHub** opens `GET /api/auth/start`, which makes a random state and PKCE verifier, stores their hashes for 10 minutes, sets both in the cookie `__Host-visto_oauth` (`Path=/; Max-Age=600; HttpOnly; Secure; SameSite=Lax`), and sends the browser to GitHub with an `S256` challenge and `allow_signup=false`.
2. GitHub returns to `GET /api/auth/callback`, which clears the cookie and goes on only when the state and verifier match what is stored and unexpired. A state is used once.
3. The code is exchanged for the person's token, which reads the account once (`GET /user`) and is dropped, not revoked: GitHub expires it after 8 hours.
4. A person let in lands on `/ui/`; a person refused lands on `/ui/signin`, which says why.

Each of these calls to GitHub ends after 10 seconds and is not retried. The state cookie is `Lax` because a `Strict` cookie is not sent on GitHub's redirect back.

### Who is let in

Only a GitHub user account, never a bot:

- **By login**: a login in `ui.accounts`, letter case aside. No further call is made.
- **By team**: otherwise, an active member of a team in `ui.team`. All teams are read at once: the app's installation on the team's organisation, then the membership through it. A pending membership does not count. By GitHub's documentation, a member of a child team reads as a member of its parent.
- The first team in written order that answers yes lets the person in and is recorded on the session. With no yes, a team that could not be read makes the refusal `unverified` with that team's reason (`github_network` after 10 seconds); otherwise it is `not_allowed`. A team that cannot be read never keeps out someone another team lets in.
- **Anyone**: otherwise, with `ui.openSignIn: true`, the person is let in as `anyone`, always a viewer, even when a team could not be read.

A person is their login: a login freed on GitHub and taken by someone else gets that login's account and role. A login with an underscore, as Enterprise Managed Users have, cannot sign in (refused as `github`).

A person let in finds their account by login, letter case aside; with none, the sign-in makes one as a **viewer**, recorded as made by `sign_in`. A role an admin sets holds for every later sign-in. With 1,000 accounts and none for this login, the sign-in is refused as `full`: "This deployment keeps 1,000 accounts at most. An admin can remove one." With `ui.openSignIn`, it first frees an idle viewer's account if it can (see [Open sign-in to anyone](#open-sign-in-to-anyone-for-a-public-demo)).

## Sessions

A session lasts 12 hours, whichever way you signed in. Its id, 32 random bytes, is the cookie `__Host-visto_session` (`Path=/; Max-Age=43200; HttpOnly; Secure; SameSite=Strict`, no `Domain`). The database keeps only its SHA-256, with the account and the way in (`password`, `account`, the team, or `anyone`).

Every API request reads its session and account from the database again:

- A role change takes effect at the person's next request.
- A GitHub session holds only while its login or team is still in the running config, or, for `anyone`, while `ui.openSignIn` is still on.
- Team membership is read only at sign-in: a member removed from the team keeps their session for up to 12 hours.
- A database failure while reading the session is not a sign-out: the request answers 500 `internal_error`.

| Event | Sessions ended |
|---|---|
| Sign out | This one: the row is deleted and the cookie cleared |
| Changing your own password | Every other session of the account |
| A reset | Every session of the account |
| A removal | Every session, with the account |
| A login or team removed from the file, then a restart | Every session that came in that way |
| `ui.openSignIn` turned off, then a restart | Every `anyone` session |

A sign-in that was checking the old password when one of these was committed is refused. A session deleted in the database reads as signed out at its next request (see [Who is signed in](#who-is-signed-in) to sign everyone out).

Requests that change something carry a CSRF token in the header `x-visto-csrf`: the SHA-256 of `csrf:` and the session id, stored nowhere and given by `GET /api/me`. Without it they are refused with 403 `csrf`.

## Accounts and roles

Each person who signs in is an account, at most 1,000 of both kinds:

- A **password account** has a name of 1 to 39 lower-case letters, digits, dots, underscores and hyphens, starting with a letter or digit, unique among password accounts.
- A **GitHub account**'s name is its login, unique among GitHub accounts, letter case aside. It may share a name with a password account; Accounts marks it `GitHub`.

An account is an `admin` or a `viewer`. A **viewer** sees every screen but Settings and cannot switch memory records: the sidebar has no Settings entry, `/ui/settings` shows the not-found page, and every admin route answers 403 `forbidden`. An **admin** also edits settings, keeps accounts and switches memory records.

When a page gets 403 `forbidden` it reads who is signed in again. An admin made a viewer loses the Settings entry at their next admin request; a viewer made an admin sees it after a reload.

### The last admin

The last admin cannot be made a viewer or removed, from the UI or the command (`last_admin`). A password admin who has not yet chosen their password does not count, so an admin cannot step down in favour of one who never signed in. A GitHub admin always counts, whatever the file says now.

With open sign-in, a GitHub account made an admin in Settings whose login is in neither `ui.accounts` nor a team still signs in as a viewer, yet counts as an admin here: keep your own login in `ui.accounts`. The command's `github --role admin` refuses such a login while no team is written.

**This can lock you out.** If the only admin is a GitHub account the file no longer lets in, or you turn GitHub sign-in off while a GitHub admin is the only admin, nobody can reach Settings. Use the command's `make` or `reset` to get a password admin back (its `github` form is refused while GitHub sign-in is off).

### Managing accounts

Admins keep accounts in Settings, under **Accounts**, which lists each account's name, kind, role, last sign-in and maker.

- **New account** takes a name and a role and shows the one-time password once, with **Copy** and **Done**. It lives only in the page and is gone after **Done**, a reload or leaving.
- **Make viewer** or **Make admin** changes the role.
- **Reset password** gives a password account a new one-time password, clears its wait, ends its sessions and keeps its role. You cannot reset your own account in the UI (409 `own_account`), so no reset can lock out its maker: use **Change password**, ask another admin, or run the command. A GitHub account has no password (409 `github_account`).
- **Remove**, confirmed in its row, deletes the account and its sessions. A removed GitHub account the file still lets in returns as a new viewer at its next sign-in.

Account changes run one at a time under a table lock that leaves reads free, and re-check the asking admin's session under it: two admins who demote each other at once leave one admin.

Every change is recorded in `visto_ai.ui_account_changes`: when, who (`by_kind` `password` or `github` with `by_name`, `command`, or `sign_in` for a GitHub row made at first sign-in, or removed by open sign-in to make room), the `change` (`made`, `role`, `reset`, `removed` or `password_changed`), the account's kind and name as text, and the new role. It has no screen (see [Who is signed in](#who-is-signed-in)).

### The accounts command

`npm run accounts` has three forms; each option appears once, in any order:

| Form | What it does |
|---|---|
| `make --config <path> --name <name> --role <admin\|viewer>` | Makes a password account and prints its one-time password and expiry |
| `reset --config <path> --name <name>` | Gives a password account a new one-time password, ends its sessions and its wait |
| `github --config <path> --login <login> --role <admin\|viewer>` | Sets a GitHub login's role, making its account if needed |

- `make` and `reset` lower-case the name, then check it: `reset --name Octo-Admin` resets `octo-admin`.
- `github` is refused while GitHub sign-in is off, printing `github sign-in is off` on stderr.
- It reads the whole config, so every variable the file names must be set.
- It never migrates: on a database without `0015_accounts` it prints `not_migrated` and writes nothing, so start the service once first.
- Its changes follow the UI's rules, the last admin included, and are recorded as made by `command`.
- npm prints two lines of its own first; scripts run `npm run --silent accounts -- ...`.

Exit codes: 0 when done; 1 for a refusal, printed as its code (`bad_login`, `name_taken`, `full`, `not_found` or `last_admin`), `not_migrated`, a failure, `github sign-in is off`, or `with open sign-in and no team, an admin login must be in ui.accounts`; 2 for a usage error, a config issue (`config: <issue>`), or a config with no database.

## The layout

The sidebar lists **Overview** (`/ui/`, where you land), **Activity** (`/ui/activity`), **Repositories** (`/ui/repositories`), **Memory** (`/ui/memory`) and, for admins, **Settings** (`/ui/settings`). Each review has a page at `/ui/reviews/<run>`, and password accounts have **Change password** at `/ui/password`. Any other address under `/ui/` says "Not found".

The sidebar also shows the mode (`Live` or `Dry run`, as the running start read it), a badge with the running reviews, who is signed in and how, a light and dark theme switch (kept in the browser, else the system's), and sign-out.

| What | Refreshed |
|---|---|
| The sidebar badge and Activity's **In review now** | Every 5 seconds |
| Activity's **Recent reviews** (first page) | Every 15 seconds |
| Overview | Every 60 seconds, health every 15 seconds |
| Repositories | Every 5 seconds while a measure is computing |
| One review, Memory, Settings | Not polled |

No page reads while its tab is hidden. A failed read turns **Updating live** into **Not updating**, and a 401 shows the sign-in page. One person on Activity or the Overview makes about 16 to 17 requests a minute.

## Overview

The Overview (`/ui/`) picks a window of **7 days**, **30 days** (the default) or **90 days**: whole UTC days ending today, so 7 days start at 00:00 UTC six days back. All cards but alerts and dependencies count within it, and the header says how many repositories were reviewed in it.

| Card | Shows |
|---|---|
| **Reviews** | Runs started, split into published, dry run, failed, nothing new and not posted (the last two only when above 0). |
| **In review now** | Jobs running, reviewing, waiting for pushes to settle and queued; links to Activity. |
| **Spend today** | The spend guard's count since 00:00 UTC (runs and the judge's calls) against `limits.spendPerDay` in force. |
| **Approved automatically** | Pull requests, each counted once by its newest published live decision: approved, or drawn for the audit (`of <n> approvable, <m> drawn for the audit`). One approved then withdrawn still counts as approved. |
| **Reviews per day** | A bar per UTC day of published, failed and other runs. Hover a bar for its counts and that day's spend, shown nowhere else. |
| **Alerts** | Open alerts (at most 50, `50+ open` when full), then the 5 newest recent ones from the last 7 days, or `No alert in the last 7 days.` |
| **Score quality by repository** | The 20 busiest repositories, with [Repositories](#repositories)' numbers. |
| **Dependencies** | Each dependency and its state. |

### Alerts

An alert is **open** while what it reports still holds, and **recent** otherwise. Nobody clears one by hand.

| Alert | Open until |
|---|---|
| `model_error`, `memory_error`, `mcp_error`, `extension_error` | Its dependency is seen working again |
| `feature_off` | A start's check of the app no longer finds the permission or event missing |
| `dismissal_failed` | No failure of a standing approval of that pull request is recorded in its run |
| `spend_80`, `spend_limit` | The UTC day it was raised on ends |
| Any other | Never open |

An open `model_error`, `memory_error`, `dismissal_failed` or `spend_limit` reads **Failing**, other open ones **Warning**. A recent alert that could have been open reads **Resolved**, the rest **Recent**.

### Score quality by repository

The 20 repositories with the most runs in the window (ties by name), then `And <n> more repositories, in Repositories.` Each row shows Safety by block from 10 labelled blocks up (below that, `Not enough labels yet, <n> of <m> blocks`), Benefit, Focus, reverts (with `(<n> approved)` when any), and automatic approval in short (`On, strict, 5% audit`, `On, gate rule, 10% audit`, `On, strict, no audit` or `Off`).

Each Overview read measures at most 2 uncached repositories; the rest read **Not measured yet** and fill in on later reads, so a cold table of 20 takes about ten minutes. Rows can be up to 15 minutes old. A failed measure reads **Could not be measured**.

### Dependencies

The review model (`model.model`), the second scorer when on (`scorer.model`), memory when learning is on, each extension's `context`, `notify` and `route` parts (`alert` has no health), each MCP server, and the GitHub App. Each reads `Working`, `Failing` with its short code and since when, or `Not checked yet`; the app reads `Missing <n>` with the first thing it lacks. A dependency switched on in Settings appears after the restart.

A state is as fresh as the dependency's last use: an MCP server no review asked for a day shows its state of a day ago. The review model is also checked at start and every 5 minutes, the app at each start, and the second scorer is judged from each review's audit, with no alert of its own.

## Activity

Activity (`/ui/activity`) shows what runs now and the reviews of the last 30 days.

**In review now** lists the jobs running or pending, at most 200, running first, each with its pull request, its [stage](#review-stages), who or what asked, when it started and a progress bar. The header counts `<r> running, <q> queued` and shows the slots of the review and withdrawal lanes; a queued job says when reviews are paused. Below come approval withdrawals waiting to retry after a failed try, at most 50, with that try's code and the time of the next.

**Recent reviews** lists runs started in the last 30 days, newest first, 25 to a page, with the total. Each shows its outcome, highest score, findings by severity, mode, cost, time taken and age, and opens [its review page](#one-review). The outcome is the first that holds: `Failed`, `Nothing new`, `Drawn for the audit`, `Approved`, `Not posted`, `Needs a person`, `Reviewed`; a dry run never reads as approved. A failed run's score reads `None`, a nothing-new one's `Kept`. Scores are red at or above the run's threshold (70 when it holds none), blue from 40, green below.

Filter by repository and by outcome (`Approved`; `Needs a person`, which includes the audit sample; `Failed`), and search by any part of the title (letter case aside, `%`, `_` and `\` literal) or by number, with or without `#`. The repository filter and search also narrow **In review now**.

## One review

Each review's page (`/ui/reviews/<run>`) is open to viewers and admins. It shows only what the service stored, reads nothing from GitHub, and is not polled.

The header shows the pull request's title, author, branches, the review's short head and **Open on GitHub**. An unknown run, or a malformed number (`/ui/reviews/007`), says **Review not found**. A selector lists the pull request's reviews, newest first, as `Review <n> of <m>` counting every run, dry and failed ones included (the newest 200 plus this one).

### Why it approved or not

The banner shows the first decision that holds: `Review failed`; `Not decided in dry run`; `Nothing new` (not posted, nothing new found); `Not posted`; `Approved automatically`; `Not approved automatically` (the review carries an approval code); `No approval decided` (posted with neither, because approval was off or the review was adopted from GitHub).

For the two automatic decisions, the banner quotes the closing paragraph of the posted review, or says `Posted as an approval.` or `Decided as <code>.` when the review has none.

Then comes **the merge gate**: the newest gate evaluation at the review's head, with its mode, state and number of blocking findings. A later review at the same head shares it.

### Scores by file

A row per scored file, reviewed files highest first (ties by path), then files not reviewed by path, at most 500.

- A file's score is its file level when that is above every block's score or no block has one, otherwise its highest block. The reason is that block's; a block scored on another pull request shows its category only, and a whole-file score shows the model's reason for the file.
- Blocks are summarised (`Whole file`, or `2 blocks, the highest at lines 38 to 51`), with `kept from an earlier review` for a reused score. A floor-raised score ends with `<given>% was given; a block this file lost had scored <score>%.`
- A file not reviewed says why (`no_diff`, `too_large`, `over_batch_limit`, `batch_failed`, `secret_file`, or another code), then ` Counted as 100%.`

### Findings

Every finding of the stored result, of four kinds (on the diff, not on the diff, on code unchanged since the last review, beyond the diff), by severity, at most 200, as plain text with backtick spans in code font. The header counts all kinds, so it can differ from Activity, which counts placed findings only. Below, the page counts the earlier threads this review judged (`n cleared, n still open`, `n could not be judged`) and the findings dropped as already discussed.

Each placed finding of a posted review shows its thread: `Thread open`, `Resolved by <login>`, `Fixed in a later review`, `Answered in its thread`, or `No thread recorded` (its comment was refused or could not be read back); one of a review not posted reads `Not posted`. The newest signal wins, a person's resolve or unresolve event or a later posted review's verdict, and a person wins a tie. So a thread a person resolved that a later review still holds open reads open.

### Side cards

- **This review**: who asked, the mode, the outcome (`Published`, `Not posted`, `Dry run`, `Nothing new` or `Failed` with its code), duration and when it was posted.
- **Usage**: the models, calls, tokens and cost, the second scorer's included.
- **Approval record**: this review's code, then the app's approvals on the pull request up to this review, newest first, at most 20, each `Stands`, `Withdrawn`, `Dismissed on GitHub` or `Withdrawal failed`, and whether it stood at a merge. A failed one reads `Dismissing it failed (<code>).`, then `Tried again in <time>.` or `Trying again now.` while a retry is pending.
- **Dependencies on this review**: the review model, memory with the records shown, lessons, and each MCP server and extension (at most 50 each), as `Working`, `Nothing to add`, `Skipped` or `Failed` with a short code. The second scorer has no row.
- **Feedback**: helpful and not helpful counts and the newest 20 reasons, with a login only when it has GitHub's shape (see [Who sees what](#who-sees-what)).

## Repositories

Repositories (`/ui/repositories`) measures how well the score tells what needs a person, from what people did on each repository's closed pull requests. It is the live form of the [Backtest](https://visto-ai.com/docs/backtest/) and counts with the same `countAt` (`src/eval/backtest/metrics.ts`), on labels built from stored comments and runs.

A tab per repository with a stored pull request (at most 200); `?repo=` picks one. Windows are **Last 30 days** (the default), **Last 90 days** and **Since install**, counting pull requests by when they closed. Admins get **Settings of `<owner>/<name>`**.

### What it shows

All at the repository's threshold in force:

- **Safety by block**: of the blocks a person stepped in on, the share left under the threshold. Lower is better; below 10 labels it says `Not enough labels yet to mean much`.
- **Benefit**: the share of pull requests where nothing reached the threshold.
- **Focus**: of the changed lines in pull requests that needed a person, the share flagged.
- **Outside signals**: reverts merged in the window, and how many undid an app approval never withdrawn; audits drawn, and how many needed a person (a strict block or file, or a merged revert).
- **At each threshold**: Safety by block and by file, Benefit and Focus at 20, 40, 70 and 90 percent and the repository's own (`current`).
- **Reviewer feedback**: helpful and not helpful answers, the share helpful, and the 5 most given not-helpful reasons, grouped by trimmed text, letter case aside (`Repeats a settled thread (3)`).
- **Blocks a person stepped in on, under the threshold**: the strict blocks the threshold left to the bot, newest first, at most 20, with path, pull request and score.

Notes say when only the newest 300 pull requests were measured, when comments or runs were cut, when pull requests were left out for unreadable scores, and `No pull request closed in this window.`

### How labels are built

- Each inline comment by someone other than the author counts, except replies in a thread started by one of the app's findings (a reply under one of its notes counts).
- A comment labels the blocks its lines meet in the run that scored its commit, or else the file.
- **Strict** means the lines changed later. The diff at merge is not stored, so a block is strict when its `hunkHash` is gone from the last run's blocks for that path, and a file when its `diffHash` differs from the last run's. A label on the last run is never strict, and changes after the last review are not seen.
- Benefit and Focus use each pull request's last run; Safety uses each labelled run, with its scores when the person commented. Every run is measured at today's threshold.

### Bounds and caching

The UI shares the database's 5 connections with the reviews, so a measure is bounded:

- It reads the newest 300 closed pull requests, at most 10,000 runs, 20,000 comments and the scores of 1,000 runs, about 4 MB per statement and per pull request. A run whose stored result is over 2 MB is skipped.
- **One measure runs at a time in the whole service.** A request waits up to 10 seconds, then is answered `computing` while the measure goes on. A measure past 60 seconds stops as `too_slow`, and a service stop ends it before its next statement.
- Results are cached 15 minutes and failures 1 minute, at most 100, by repository, window and threshold. A repository with no stored pull request is answered at once and not cached.
- At worst a measure holds one connection for about 75 seconds and peaks at about 45 MB of heap (about 100 MB for highly compressed scores).

## Memory

Memory (`/ui/memory`) lists what the service learned from people, reverts and replies, which later reviews are told as context (see [Memory](https://visto-ai.com/docs/memory/) and [Lessons and reverts](https://visto-ai.com/docs/lessons-and-reverts/)). It lists every record that has not expired, on or off, newest first, 50 to a page. Filter by kind (`People stepped in`, `Reverts`, `Lessons`) and repository, and search up to 100 characters across path, directory, a person's words or the lesson.

Each row shows its kind; its text (the start of what the person wrote, at most 200 characters, or `A person commented on these lines.`; the lesson; or a sentence for a revert; a lesson's quote is not shown); its path or directory and repository; its source (`#<n>, by <login>`, `#<n> reverted #<m>` or `A reply on #<n>`); when it was made and expires (`Unknown`, `Never`); and whether it is on. The page counts records on by kind and records off, and says whether learning was on at start and when the learning work last ran.

### Switching a record off

Only admins switch records; viewers see the switches disabled. Off moves the record's `status` from `active` to `disabled`, on moves it back, and only an unexpired record can be switched. Every reader of memory reads `active` records only, and a review reads memory once, when it packs its files, so a switch applies from the next review. Learning never switches a record back on, and the judge does not remake a lesson that is off.

**Switching a record off does not lower a score already given**: a block scored while the record was on keeps that score in the score history until its code changes (see [Scores across reviews](https://visto-ai.com/docs/scores-across-reviews/)).

A switch is not a setting and is not in Settings' **Changes**; the record keeps only who switched it last (`switched_by`) and when (`switched_at`).

## Settings

Settings (`/ui/settings`) is for admins. Its sections are **General**, **Model**, **Repositories**, **Secrets**, **Access**, **Accounts**, **Changes** and **In config.yml**. Once the service has started, the editable part of the config lives in its database; [Configuration](https://visto-ai.com/docs/configuration/) lists it and explains how the file and the database stay in step.

### What you can edit

| Section | Settings |
|---|---|
| **General** | Dry run, learning, the daily spend limit, the reviews at once, the input tokens per call, the batches per review |
| **Model** | The model, fallbacks, the two efforts (`Provider default`, `Low`, `Medium`, `High`), how the answer is asked for, the time limit, the three prices, the extra body and extra headers (JSON text), and the second scorer's model and time limit |
| **Repositories** | `Defaults for all`, and per-repository overrides in **Review**, **Score**, **Merge gate** and **Automatic approval** |

Read only, because only the file sets them:

- **The endpoints** (`model.baseUrl`, `scorer.baseUrl`), marked `Set in config.yml`: the API keys are sent to them, so only whoever edits the file may change them.
- **Secrets**: each secret by its variable's name, as `Set` or `Not set`, never its value. An unwritten audit key reads `Generated by the service, kept in its database`.
- **Access**: the address, and who may sign in through GitHub.

The second scorer is on while its model or time limit is written. Its key stays in the file, so switching it on is refused, with the key's issue at the top of the page, unless the file writes `scorer.apiKey`. An effort the file writes as another value reads `As written in config.yml` until you pick one.

In **Repositories**, **Add a repository** takes an `owner/name`, kept once it overrides a setting. Each setting reads `From the defaults` or `Overrides <default>` with **Use the default**. In **Reviewed on every push**, `*` means every branch; in **Gated branches**, `*` is a branch of that name.

Each setting shows where its value came from: `From config.yml at the start of <time>`, `Changed in the UI by <name>, <time>`, `The default`, or `Not written` (taken back on the page, not yet saved).

### Saving

The header says "Saved settings apply from the next review. A review already running keeps the settings it started with.", counts unsaved changes, and has **Discard** and **Save changes**. Save is off while nothing changed, while a save is in flight, and while a JSON field is invalid.

- A save sends only what you changed, with the version the page read.
- **If someone saved first**, the page says "Settings were saved meanwhile, here or in config.yml at a start. They were read again, and your changes are kept: save again."
- A refusal shows each issue under its setting and all of them at the top.
- A save is checked both as what the next start would run on and as what runs until then; if either fails, nothing is stored.
- Leaving or reloading the page drops unsaved changes without warning.

### Settings that restart the service

These are read only at start and carry **Needs a restart**: dry run, learning, the reviews at once, the model's time limit and how the answer is asked for. Turning the second scorer on or off carries **On or off: needs a restart**.

When a save changes one of them from what the running start read, the page warns "Saving this restarts the service." Then:

1. The save is answered with `restarting: true` and the service logs `restarting`.
2. It stops as on a signal: running reviews finish (up to 10 minutes), requests in flight are answered, and the process exits with code 75.
3. Its supervisor starts it again: Compose does, with the `restart: unless-stopped` in [compose.yaml](https://raw.githubusercontent.com/visto-ai/visto-ai/0faf484aa43f4fcdc1f30c1d5c056ea26c1c0d32/compose.yaml), and so does Kubernetes. **A process with no restart policy stays stopped.**
4. The page asks every 3 seconds until a newer start answers, then says "The service restarted. The saved settings are in force." After 15 minutes it says the service has not come back and to check its logs.

Until then, such a setting says `Takes effect when the service restarts`. A save that sets a value back to what the start read restarts nothing.

### Changes and In config.yml

**Changes** records every change, newest first, 50 to a page: when, who (`config.yml` or an account's name), where, the setting, and its value before and after. A change in the file is recorded at the start that read it.

**In config.yml** shows the saved settings as the file writes them, with **Copy**: replace those keys in your file to keep it in step. The service never writes the file.

**`model.extraBody` and `model.extraHeaders` take no secret reference.** Whatever the file writes there, a header token included, is shown to admins, stored in the settings tables, recorded and exported. Keep keys in `model.apiKey` or `scorer.apiKey`. An endpoint with a credential in it (`https://user:token@...`) is shown to admins and in the export, but not stored in the settings tables.

## Change password

**Change password** (`/ui/password`) is for password accounts; GitHub accounts get the not-found page. It takes the current password and the new one twice, and ends the account's other sessions. A wrong current password counts toward the wait, and while the account waits the change is refused (`wrong_password`).

## Who sees what

Everyone signed in, admin or viewer, sees the same data for every repository the service holds records of. **Nothing narrows this to a person's access on GitHub**: someone with no read access to a repository still sees its pull request titles, authors and branches; the login of whoever asked for a review with `/review` or `/done`; the model's own words on each review page, including reasons below the threshold and dry-run findings that **never appeared on GitHub**; who resolved each thread; feedback reasons; and in Memory, the start of what people wrote (one line of at most 200 characters) with their logins.

A login beside a feedback reason is what an extension module reported, unverified, and is shown only when it has GitHub's shape. No answer holds the loaded config, a secret, a review's posted body or comments, the model's summary, a quote of code, thread replies or GitHub's ids, and no answer but the one that made it holds a one-time password.

## Security

**Requests from other sites.** Password sign-in creates a session without one, so it is accepted only with an `Origin` exactly equal to `ui.publicUrl` (else 403 `origin`) and `content-type: application/json` (else 415 `not_json`), checked first. Scripts must send `Origin`. Every change behind a session needs the CSRF token, every body must be JSON, and the session cookie is `SameSite=Strict`.

**Headers.** Every UI answer, the listener's own 503, 413 and 500 included, carries `content-security-policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self'; manifest-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'`, `x-content-type-options: nosniff`, `referrer-policy: same-origin` and `x-frame-options: DENY`. Fonts are bundled and nothing loads from another origin. Files under `/ui/assets/` (hashed names) are cached for a year (`public, max-age=31536000, immutable`); everything else, `index.html` and the API included, is `no-store`. The built files hold no data and are served to anyone; their paths are never decoded or joined to a folder.

### Limits

| Limit | Value |
|---|---|
| Session | 12 hours |
| GitHub sign-in state | 10 minutes; past 1,000 live, `GET /api/auth/start` answers 503 `busy` |
| One-time password | 72 hours |
| Wrong passwords | 5 in a row, then a 15-minute wait |
| Accounts | 1,000; with `ui.openSignIn`, a viewer a sign-in made and idle 30 days is freed for a new one |
| `ui.accounts` / `ui.team` | 100 logins / 10 teams |
| Request body | 64 KiB (413 `payload_too_large`) |
| Concurrent file requests (`/`, `/ui`, `/ui/...`) | 16, served from memory |
| Concurrent sign-in requests (the four sign-in routes) | 2 |
| Concurrent other `/api` requests | 4 |

These slots are the UI's own, apart from the webhook's 20 and each extension module's 10; a request beyond them is 503 `busy`. So at most 6 UI requests use the database at once, sharing its 5 connections with the reviews. A flood of sign-ins can hold sign-in off (GitHub starts for up to 10 minutes), while `/api/auth/ways` stays answerable from the API's slots. Expired sessions and states are deleted at sign-in, at most once a minute.

## Operations

### Alerts and dependency state

Every alert except the four that close a pair (`model_ok`, `mcp_ok`, `extension_ok`, `memory_ok`) is stored in `visto_ai.alerts` as well as logged and posted, in dry run and with the UI off too, with its code, its key (such as the server or `<repo>#<number>`), a short allowlist of details (never a secret, login or person's text), and when it was raised and cleared. Each dependency's state is a row of `visto_ai.dependency_health`.

- When a dependency is seen working, every open alert of its key is cleared. The first note after each start is always written, since a restart forgets the in-memory state.
- An alert raised while one of the same key is open is not stored again, so later reasons are only in the log. Nor is a spend alert raised again the same UTC day after a restart.
- Each start clears open `feature_off` alerts, then raises again what is still missing.
- **Writes never hold a review.** They queue, at most 200 (one more is dropped as `status_store_full`); a failed write logs `status_store_failed`. A state is rewritten when it changes or a minute after its last write, so "checked 2 min ago" can lag a minute.
- Alerts older than 30 days are deleted every 5 minutes, except open ones.

### Review stages

Each review job writes its stage, with the UI off too:

| Stage | When |
|---|---|
| `Waiting for pushes to settle` | A push's job (`synchronize`) in its 180 quiet seconds |
| `Waiting to try again` | Any other pending job not yet due, such as one put back after a failed try or because the head moved |
| `Queued` | A pending job that is due |
| `Preparing` | Written first; also a running job with no stage yet |
| `Reviewing`, batch n of m | Before the first batch is sent and as each batch ends |
| `Judging threads`, with the threads due | While a batch holding a thread owed a verdict runs; such files go first |
| `Publishing` | Just before posting, so never in dry run |
| `Stopped` | A running job this service does not hold, left by a job that could not record its run; it runs again at the next start |

The progress bar moves only as batches end (5% preparing, `10 + 80 * (n - 1) / m` percent at batch n of m, 95% publishing). After a crash, the next start puts running jobs back, so they read `Queued`.

### With the UI off

The service still stores titles, stages, retry codes, alerts and dependency states. It still syncs settings at each start, but copies the file's editable part whole: anything saved in the UI is overwritten (recorded as changed by `config.yml`). Nothing of the accounts is read. A pull request stored before the UI existed shows `<owner>/<name> #<number>` until its next delivery.

### Migrations

| Migration | Adds |
|---|---|
| `0014_ui` | Titles on `pull_requests`, stage columns and a retry code on `jobs`, and `ui_sessions` and `ui_states` |
| `0015_accounts` | `ui_accounts`, `ui_account_changes`, and each session's account. It deletes every session, so everyone signs in again once. |
| `0016_settings` | `settings`, `settings_file` (the file's editable part at the last start) and `setting_changes`. The first start after it copies the file in. |
| `0017_overview` | `alerts`, `dependency_health`, and `switched_at` and `switched_by` on `memory_records` |

They apply whether or not the UI is on. A previous release refuses to start on a database with a migration it does not know (`unknown_migration_applied`), so you cannot roll back past one.

### The log

No log line holds a login, name, password, one-time password, hash, code, state, verifier, token, cookie, session id or the client secret; who did what is in the database.

| Event | When, and its fields |
|---|---|
| `ui` | At start, with `files` |
| `ui_signin` | Each GitHub callback and each password request the route answers, with `way`, `outcome` and `reason` |
| `ui_account` | Each account change through the service, with `change` and the new `role`. The command logs nothing. |
| `ui_failed` | A failed request, with the route's name (such as `settings_save` or `quality`) and a short code |
| `settings` | Each start, with `from_file` (settings the file changed) and `from_ui` (settings whose value came from the UI) |
| `settings_save` | Each save, with `outcome` (`saved`, `changed` or `invalid`) and `changes` |
| `restarting` | A save that restarts the service |
| `memory_switch` | Each switch that changed a record, with `record` and `on` |
| `status_store_failed`, `status_store_full` | A failed or dropped write of an alert or dependency state, with `what` (`alert`, `health`, `clear` or `prune`) |
| `quality_failed` | A failed score-quality measure, with a short code such as `too_slow` |

`ui_signin` outcomes with `way` `github`: `ok`, `denied` (refused on GitHub's page), `state`, `github` (GitHub unreachable, refused the code, or gave an unexpected answer), `not_allowed`, `unverified`, `full` and `failed` (a database step). The `reason` is a short code such as `oauth_refused`, `github_502` or `not_installed`, or null. With `way` `password`: `ok`, `choose` (a right one-time password), `refused`, `expired`, `already_chosen`, `bad_request` with its code as the reason (`origin`, `not_json`, `bad_request`, `password_length` or `same_password`), and `failed` with a short code. Other password outcomes have no reason, so a password typed into the name field is never logged. Requests refused as busy or too large write no line.

### Database queries

Run these in the service's database (`docker compose exec db psql -U postgres -d visto`).

#### Who is signed in

```sql
-- who is signed in now, and as whom (an `anyone` session is a viewer whatever a.role says)
select a.kind, a.name, case when s.via = 'anyone' then 'viewer' else a.role end as role, s.via, s.created_at, s.last_used_at, s.expires_at
from visto_ai.ui_sessions s join visto_ai.ui_accounts a on a.id = s.account_id where s.expires_at > now() order by s.last_used_at desc;
-- the record of account changes, newest first
select at, by_kind, by_name, change, account_kind, account_name, role from visto_ai.ui_account_changes order by at desc, id desc limit 100;
-- sign everyone out
delete from visto_ai.ui_sessions;
```

#### The settings, and who changed them

```sql
-- the settings in the database, and where each came from
select scope, path, value, set_by, set_by_name, set_at from visto_ai.settings order by scope, path;
-- the latest changes
select at, by, by_name, scope, path, old_value, new_value from visto_ai.setting_changes order by id desc limit 50;
```

`settings_file` holds the file's editable part as of the last start, which the next start compares the file with. A setting not in `settings` reads as its default.

#### Alerts, dependencies and memory switches

```sql
-- alerts not cleared, newest first (the Overview also closes spend alerts at the end of their UTC day,
-- and a withdrawal's alert with its stored failure)
select id, code, key, details, raised_at, cleared_at from visto_ai.alerts where cleared_at is null order by raised_at desc limit 50;
-- each dependency's state, and since when
select kind, name, part, status, code, since, seen_at from visto_ai.dependency_health order by kind, name, part;
-- who switched memory records, latest first (never switched: switched_at is null)
select id, owner, repo, kind, status, switched_by, switched_at from visto_ai.memory_records where switched_at is not null order by switched_at desc limit 50;
```

## API reference

The UI is a React app over a JSON API under `/api/`. Every route but `/api/auth/ways` and the four sign-in routes needs a session (else 401 `signed_out`). **Admin** routes answer viewers 403 `forbidden`; **token** routes need the CSRF token.

| Route | What it does |
|---|---|
| `GET /`, `GET /ui` | Redirects to `/ui/` (302) |
| `GET /ui/...` | A built file; any other address gets `index.html`, but a missing file under `/ui/assets/` is 404 |
| `GET /api/auth/ways` | `{ "github": true }` or `{ "github": false }` |
| `GET /api/auth/start`, `GET /api/auth/callback` | Sign-in through GitHub; 404 while it is off |
| `POST /api/auth/password` | `{ "name", "password" }`: `{ "next": "signed_in" }` with the cookie, or `{ "next": "choose_password" }` |
| `POST /api/auth/first-password` | `{ "name", "oneTimePassword", "password" }`: `{ "next": "signed_in" }` with the cookie |
| `POST /api/auth/signout` | Token. 204 |
| `GET /api/me` | Your name, kind and role, the CSRF token, `live` or `dry_run`, and the repositories with a stored pull request (at most 200) |
| `POST /api/me/password` | Token. `{ "current", "password" }`: 204 |
| `GET /api/activity` | **In review now** |
| `GET /api/reviews?repo=&outcome=&q=&before=` | A page of Recent reviews; `outcome` is `approved`, `needs_person` or `failed`, `before` the run to page from |
| `GET /api/reviews/<run>` | One review |
| `GET /api/pulls/<owner>/<name>/<number>/reviews` | A pull request's reviews, at most 200, with their place and the total |
| `GET /api/accounts` | Admin. Every account |
| `POST /api/accounts/new` | Admin, token. `{ "name", "role" }`: 201 with the account and its one-time password |
| `POST /api/accounts/role` | Admin, token. `{ "id", "role" }`: 200 |
| `POST /api/accounts/reset` | Admin, token. `{ "id" }`: 200 with a new one-time password |
| `POST /api/accounts/remove` | Admin, token. `{ "id" }`: 204 |
| `GET /api/settings` | Admin. Every setting with its value, source and restart state, the `version`, `started`, the endpoints, the secrets (never a value) and access |
| `PUT /api/settings` | Admin, token. `{ "version", "changes": [{ "scope", "path", "value" }] }`, 1 to 500 changes, none twice; scope `global`, `defaults` or a lower-case `owner/name`; no `value` restores the default. 200 with the settings and `restarting`, 409 `changed`, or 422 `invalid` with `issues` |
| `GET /api/settings/changes?before=` | Admin. Up to 50 changes, newest first, and `next` |
| `GET /api/settings/export` | Admin. `{ "text" }`, the saved settings as `config.yml` text |
| `GET /api/overview?days=` | The Overview; `days` 7, 30 or 90 (default 30) |
| `GET /api/health` | Dependencies, open alerts (at most 50) and recent ones (at most 5) |
| `GET /api/repositories` | Repositories with a stored pull request, at most 200 |
| `GET /api/repositories/<owner>/<name>/quality?days=` | `days` 7, 30, 90 or `all` (default 30). 200 with `state` `ready`, `computing` or `failed`, never 500 |
| `GET /api/memory?kind=&repo=&q=&before=` | A page of records; `kind` is `human_signal`, `revert` or `lesson` |
| `PUT /api/memory/<id>` | Admin, token. `{ "on": true }` or `{ "on": false }`: 200 with the record; 404 if missing or expired |

### How requests are checked

Checks run in this order, and nothing is read after a refusal: the session (401 `signed_out`), the CSRF token (403 `csrf`), the admin role (403 `forbidden`), `content-type: application/json` (415 `not_json`), then a JSON object of exactly the route's keys (400 `bad_request`). An empty query parameter reads as absent and a malformed one is 400 `bad_request`. A path that does not fit a route exactly (an id with a leading zero or outside 1 to 2147483647, a malformed owner or name, a trailing slash) is 404 `not_found` and reads nothing; a wrong method is 405 with `allow`. Refusals at `/api` are JSON, `{ "error": "<code>" }`; the files' 404 and 405 and the listener's 503 and 413 are plain text.

### Error codes

| Status | Codes |
|---|---|
| 400 | `bad_request` (a malformed body, parameter or path), `bad_name`, `password_length` (outside 12 to 128 characters), `same_password` (a first password equal to the one-time password), `wrong_password` (a wrong current password, or a waiting account) |
| 401 | `signed_out` (no session, or it ended), `refused` (wrong name or password, a waiting account, or a first password beaten by a reset), `expired` (an expired one-time password) |
| 403 | `csrf` (no CSRF token), `forbidden` (a viewer at an admin route), `origin` (a password sign-in from another origin) |
| 404 | `not_found` (no such account, run, record or route) |
| 409 | `already_chosen`, `name_taken`, `full` (1,000 accounts), `last_admin`, `github_account` (a password action on a GitHub account), `own_account` (resetting your own account), `changed` (someone saved the settings first) |
| 413 | `payload_too_large` (a body over 64 KiB) |
| 415 | `not_json` |
| 422 | `invalid` (a settings save with issues) |
| 500 | `internal_error` (a failure, logged as `ui_failed`) |
| 503 | `busy` (no free request slot, or 1,000 live GitHub states) |

## Related

- [Configuration](https://visto-ai.com/docs/configuration/): the editable settings, and how the file and the database stay in step.
- [Creating the app](https://visto-ai.com/docs/create-the-github-app/): the GitHub App and its client id and secret.
- [Running the service](https://visto-ai.com/docs/running-the-service/): restarts, alerts and operations.
- [Memory](https://visto-ai.com/docs/memory/) and [Lessons and reverts](https://visto-ai.com/docs/lessons-and-reverts/): what the Memory screen lists.
- [Backtest](https://visto-ai.com/docs/backtest/): the offline form of Repositories.
