# UI kit (TypeScript)

Reference for @omazyai/sdk/ui and @omazyai/sdk/ui/react. The copilot panel with consent, approval and actor cards, an approvals inbox with a step-up slot, connected apps, a "what we remember" page and standing grants. Unstyled, themeable, English and Bangla.

Source: https://docs.omazy.ai/build-on-omazy/kits/ui/

:::caution[Preview]
The kit is a preview in `@omazyai/sdk` 0.5.3. Its interface may change before 1.0, so pin the exact version. It is TypeScript only.
:::

```ts
import { uiRoutes } from '@omazyai/sdk/ui/server'                 // on the server
import { CopilotPanel, ApprovalsInbox, UiProvider } from '@omazyai/sdk/ui/react'   // in the page
import '@omazyai/sdk/ui/styles.css'                                // optional
```

The screens a person uses to work with the other kits: the [copilot](/build-on-omazy/kits/copilot/)
conversation and its cards, the [guard's](/build-on-omazy/kits/guard/) approvals, the
[oauth kit's](/build-on-omazy/kits/oauth/) connected apps and keys, the
[ai kit's](/build-on-omazy/kits/ai/) memory, and standing grants.

The kit has three entries:

| Entry | Holds | Needs |
|---|---|---|
| `@omazyai/sdk/ui` | A chat on the AI SDK UI message stream, fetch clients, view models for each card and screen, the text in English and Bangla, and the stylesheet as a string. No server code | Nothing |
| `@omazyai/sdk/ui/server` | `uiRoutes`, the server half | The kits it is given |
| `@omazyai/sdk/ui/react` | The components and hooks | React 18.2 or later, an optional peer dependency |

A product on Preact, or on no framework, uses the first entry and renders the view models itself.
The kit has no other dependency. It does not import `ai` or `@ai-sdk/react`, and the panel still
takes a `useChat` result if the product has one.

## On the server

`uiRoutes` answers the screens' requests from the kits the product already runs. The product
builds the ctx from its own session, as for any route, with a channel where a person acts
(`console`), so memory and grants accept the change.

```ts
import { uiRoutes } from '@omazyai/sdk/ui/server'

const ui = uiRoutes<Ctx>({
  approvals: { guard, store: guardStore, reviewUrl: (a) => `/approvals/${a.id}`, codes },
  apps: oauthServer,              // createOAuthServer(...): connectedApps, revokeApp, keys
  memory: ai.memory,              // or createMemory(...)
  grants,                         // createGrants(...)
  registry,                       // titles, and the R2 capabilities a grant may name
  grantable: unit.tools.allow,    // optional: only the copilot's own tools
})

// in the Worker's fetch
const res = await ui.handle(req, consoleCtx(req), { waitUntil: (p) => ctx.waitUntil(p) })
if (res) return res
```

Give only the parts the product has; a screen without its part gets no route. The routes, under
`/ui` by default (`base` changes it):

| Route | Does |
|---|---|
| `GET /ui/approvals?status=waiting` | Approvals this person may see: `waiting` (default), `all` or one status |
| `GET /ui/approvals/<id>` | One approval, 404 when the person may not see it |
| `POST /ui/approvals/<id>/code` | With `approvals.codes`: sends a step-up code to whoever may decide it now. Answers `{ channels, method, expiresAt }`; 404 to someone who may not see it, 403 to someone who may see it but not decide it, 409 once it is decided, 400 when its policy asks for another method |
| `POST /ui/approvals/<id>/decide` | `{ approve, reason?, typedTarget?, proof? }` to `guard.decide`. The proof is the product's, passed through |
| `GET /ui/apps` | Connected apps and keys of this person |
| `POST /ui/apps/<grantId>/revoke` | Disconnects one app |
| `POST /ui/keys/<id>/revoke` | Revokes one key |
| `GET /ui/memory` | This person's memory and their tenant's, with the unit and run that suggested each |
| `POST /ui/memory/<id>/confirm`, `/reject`, `/forget` | One memory |
| `GET /ui/grants` | The person's grants, what is left today, and the R2 capabilities they may allow |
| `POST /ui/grants` | `{ capability, days, dailyCap }` to `grants.set` |
| `POST /ui/grants/<id>/revoke` | One grant |

What the routes keep back:

- **An approval is listed only to its requester, its decider, and whoever may decide it now**
  (`guard.canDecide`), and only within the person's tenant. `canSee(ctx, row)` widens that, for
  example to every owner of the tenant. The sealed arguments and their hash never leave the
  server; the inbox shows the preview stored with the request, which is what the decider approves.
- Connected apps leave out the seat id, keys leave out the owner, memory leaves out the ids it
  mentions.
- A `POST` must be `application/json`, so a plain form on another site cannot send one. Every
  answer is `cache-control: no-store`.
- **A step-up code goes only to someone who may decide the approval now.** `codes` is the guard's
  `codeStepUp`, the same object given to `createGuard`'s `stepUp`:

  ```ts
  const codes = codeStepUp<Ctx>({ store: guardStore, send: (ctx, channel, code) => mail.send(ctx.principal.id, code) })
  const guard = createGuard({ ...options, stepUp: [codes] })
  ```

  Each request sends a fresh code and the earlier one stops working. The kit sets no limit on how
  often a person may ask, so rate-limit the route as you would any message you send. The code
  itself never comes back in the answer.

The copilot's own routes stay where `copilot.handle` serves them, `/copilot` by default.

## In the page

```tsx
import { ApprovalsInbox, ConnectedApps, CopilotPanel, MemoryPage, StandingGrants, UiProvider } from '@omazyai/sdk/ui/react'

<UiProvider locale="bn" copilotBase="/copilot" uiBase="/ui">
  <CopilotPanel thread={threadId} screen={{ name: 'tenant', id: tenantId }} />
  <ApprovalsInbox stepUp={(s) => <MyPasskeyPrompt approval={s.approval} onProof={s.done} onCancel={s.cancel} />} />
  <ConnectedApps />
  <MemoryPage />
  <StandingGrants />
</UiProvider>
```

`UiProvider` sets the language, the text, the `fetch` and its headers, and where the routes are.
Without it the components use English, the global `fetch`, `/copilot` and `/ui`. With
`uiBase={null}` the product mounts no `uiRoutes`: approval cards then show the status the thread
holds and fetch none.

## The copilot panel

`CopilotPanel` loads the thread's history, sends each message with the screen, reads the reply as
it streams, and draws each part:

| Part | Drawn as |
|---|---|
| `text` | A paragraph |
| `data-consent` | `ConsentCard`: the title, the preview's sentence, a table of the fields that change (before and after, changed fields first), the expiry, and Confirm and Decline. The click posts the card id to `…/cards/<id>/confirm` or `/decline` and the card takes the outcome |
| `data-approval` | `ApprovalCard`: who decides, the expiry, the review link while it waits, and the status with its reason. With `uiRoutes` it fetches the status every 15 seconds (`approvalPollMs`) until it settles. Events on the thread will replace the polling when the copilot's stream resume lands |
| `data-actor` | `ActorCard`: the actor's state and progress, its question with the choices as buttons (a choice is sent as the person's next message), its card's rows with Confirm and Decline, who decides when it waits for approval, and "Continue in the form" with the hand-off link and its pre-fill |
| `data-memory` | `MemorySuggestion`: the text, and Remember and Do not remember when `uiRoutes` is mounted |
| `dynamic-tool` | Nothing. `renderPart` can draw it |

An `error` chunk or a refused request becomes one sentence in an alert under the conversation,
the server's own words when it gave them. A busy thread or a card no longer on the thread says so
on the card.

The panel runs its own chat, or one the product passes:

```tsx
import { useChat } from '@ai-sdk/react'
import { DefaultChatTransport } from 'ai'

const chat = useChat({ id: threadId, messages: initial, transport: new DefaultChatTransport({ api: '/copilot/chat' }) })
<CopilotPanel thread={threadId} chat={chat} />
```

`useCopilotChat({ thread })` is the panel's own chat as a hook, with the same fields `useChat`
returns (`messages`, `status`, `error`, `sendMessage`, `setMessages`, `stop`). It sends only the
new message; the copilot keeps the history on the server and reads only the last user message
anyway.

## The approvals inbox

`ApprovalsInbox` lists the approvals waiting (or all of them) and opens one in `ApprovalDetail`:
the stored preview, the tier, who decides, who asked and when, the expiry, and the decision once
there is one.

**Approving runs the product's step-up first.** The kit opens a slot and renders what the
product's `stepUp` returns there. The product asks for its passkey or sends and checks its code,
then calls `done(proof)`. The kit sends the proof with the decision to the guard, untouched. It
never sees a passkey assertion or a code.

```tsx
<ApprovalsInbox
  stepUp={({ approval, methods, done, cancel }) => (
    <PasskeyButton
      challengeFor={approval.id}
      onAssertion={(assertion) => done({ method: 'passkey', assertion })}
      onCancel={cancel}
    />
  )}
/>
```

For the guard's `codeStepUp`, `CodeStepUpForm` is the slot, ready made. It asks
`POST …/approvals/<id>/code` to send the code, shows where it went, gives a field for each channel
(`autocomplete="one-time-code"`), and calls `done({ method, codes })` with what the person typed.
**Send a new code** asks again; Cancel and Escape go back to Approve.

```tsx
<ApprovalsInbox stepUp={(s) => <CodeStepUpForm {...s} />} />
```

It needs `uiRoutes` with `approvals.codes`. A product that sends codes some other way, or asks
for a passkey, writes its own slot as above.

Without `stepUp`, an approval that needs one says the page cannot verify it. A policy that asks
the decider to type the target shows a field for it first. Someone who may not decide sees why,
and no buttons.

**Refusing needs a reason and no step-up**, as in the guard. Refusing is the safe direction, like
turning a switch off: nothing runs and nothing changes, so there is nothing for a hijacked session
to gain from it.

The inbox reloads its list every 30 seconds (`pollMs`), and an approval card in the panel every 15.
Events will replace the polling when the copilot's stream resume lands.

## Settings screens

- **`ConnectedApps`**: each app with its verified status, door, when it connected and was last
  used, and each personal or service key. Revoke asks once more before it acts.
- **`MemoryPage`** ("What we remember"): suggestions waiting for the person, with Remember and Do
  not remember; then what is remembered, about the person or the organisation, with the unit that
  suggested it, who confirmed it and when, and Forget.
- **`StandingGrants`**: the grants in force with what is left today, Revoke, and a form to allow
  one R2 change for a number of days and runs a day. The limits come from the copilot kit (90 days,
  500 a day). Approvals are never waived.

## Text

Every word is in `UI_TEXT.en` and `UI_TEXT.bn`. Pick one with `locale`, and change any word:

```tsx
<UiProvider locale="bn" text={{ decline: 'বাদ দিন', cardStatus: { confirmed: 'হয়ে গেছে।' } }}>
```

A record such as `cardStatus` merges key by key. Numbers and dates go through `Intl` in the
locale. **Bangla always uses Bengali digits**: its tag is `bn-BD-u-nu-beng`, because some runtimes
(Bun, some Node builds) give a plain `bn-BD` Latin digits. A product that sets `locale` to another
`bn` tag gets `-u-nu-beng` added unless the tag names a numbering system (`intlLocale` does it).
The composer leaves Enter to the input method while it composes, so
typing Bangla does not send half a word. Words that come from the server (a preview's sentence,
an error) are shown as the server wrote them.

## Styles

The components are unstyled. Each carries `omz-*` class names, `data-status` with its state, and
ARIA state, for the product's own design system. Each top-level component also takes `className`.

`@omazyai/sdk/ui/styles.css` (also `UI_CSS` in the core) is a small default that reads only CSS
variables on `.omz`:

```css
.omz { --omz-accent: #0f766e; --omz-radius: 4px; --omz-font: 15px/1.5 Inter, sans-serif; }
```

The variables: `--omz-font`, `--omz-fg`, `--omz-muted`, `--omz-bg`, `--omz-surface`,
`--omz-border`, `--omz-accent`, `--omz-accent-fg`, `--omz-danger`, `--omz-ok`, `--omz-warn`,
`--omz-focus`, `--omz-radius`, `--omz-gap` and `--omz-transition`, with a dark set under
`prefers-color-scheme: dark`. Under `prefers-reduced-motion: reduce` it stops every animation and
transition, and the panel stops scrolling smoothly.

The kit adds no `<style>` or `<script>` to the page, so it runs under a content security policy
with `script-src 'self'` and `style-src 'self'`.

## Keyboard and screen readers

- Every action is a native button or link with a visible focus ring.
- Each card is an `article` named by its heading. A click's outcome is spoken from a status line,
  which takes the focus, so the person hears what happened and stays on the card.
- The conversation is a `log` region; the composer has a label and a hint. Enter sends, Shift and
  Enter starts a new line.
- In the inbox the arrow keys, Home and End move between requests. Opening one moves focus to its
  heading. Escape closes the step-up slot (focus returns to Approve), the refusal form, then the
  detail.
- Revoke and Forget ask once more; Escape or Cancel goes back with focus on the button.

## Without React

```ts
import { approvalView, consentView, copilotClient, createChat, partView } from '@omazyai/sdk/ui'

const copilot = copilotClient({ base: '/copilot' })
const chat = createChat({ api: copilot.chatUrl, id: threadId, messages: (await copilot.history(threadId)).messages })
chat.subscribe(() => render(chat.getSnapshot()))      // { messages, status, error }
await chat.sendMessage({ text })

for (const part of message.parts) {
  const v = partView(part)                            // text, consent, approval, actor, memory, tool
  if (v.kind === 'consent') draw(consentView(v.card)) // rows, status, expiry, canAct
}
```

`uiClient({ base: '/ui' })` speaks to `uiRoutes`. `createResource(load, { pollMs })` is the small
store the React hooks use, with `subscribe` and `getSnapshot` for any framework.

## Example

`sdk/typescript/examples/copilot-worker.ts` and `copilot-page.ts`: the notes product's page runs
the copilot panel, the standing grants section and the approvals inbox, bundled to `/app.js` and
served as a static asset, with `uiRoutes` at `/ui/` and a strict content security policy. Add
`?lang=bn` for Bangla and `?as=u_owner` to act as the owner.

The owner's step-up is the guard's `codeStepUp`. **Demo only:** so the approve path can be tried
without a mail sender, the Worker hands the code to the page when `DEMO_STEP_UP_CODES=1` (set it in
`.dev.vars` for `wrangler dev`, never in `wrangler.toml` or a deployed Worker; without it the route
answers 404), and the page shows it only in a development build. A minified production build of
the page drops that code path. A product sends the code by email or SMS, or asks for a passkey,
and never shows it on the page.

Its workerd test renders the page in a light DOM against the Worker under Miniflare: a message,
the consent card from the stream, the click that runs it, and a standing grant; then a share that
needs the owner, approved in the inbox with the demo code and run once.
