---
title: App UI SDK
description: Embed the Anna App SDK in your bundle and call host APIs from inside the iframe.
section: apps
slug: app-ui-sdk
updated: 2026-11-27
estimated_minutes: 5
category: App UI
---

The Anna App SDK is a single ESM file the host serves at:

```
/static/anna-apps/_sdk/latest/index.js
```

It runs **inside your iframe**, talks to the parent window over `postMessage`, and exposes a typed runtime object you use to call the host. It is a native ES module (it `export`s `AnnaAppRuntime`; there is no `window` global), so you load it with a single `<script type="module">` + `import` — the SDK origin is automatically allow-listed in your bundle's `script-src`.

## Minimum bundle

```html
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <title>My App</title>
  <link rel="stylesheet" href="./assets/app.css" />
</head>
<body>
  <main id="root">Loading…</main>
  <script type="module">
    import { AnnaAppRuntime } from "/static/anna-apps/_sdk/latest/index.js";

    const anna = await AnnaAppRuntime.connect();
    document.getElementById("root").textContent =
      anna.runtimeState?.notes ?? `Hello, ${anna.viewMeta.title}!`;

    // Persist on user input (debounce yourself)
    document.addEventListener("input", e => {
      anna.storage.set({ key: "notes", value: e.target.value });
    });
  </script>
</body>
</html>
```

That's it. No bundler is required; ESM imports work because the host serves the SDK with `Content-Type: application/javascript` and the bundle CSP already allows `script-src 'self' <sdk-origin>`.

## `AnnaAppRuntime.connect()`

```ts
const anna = await AnnaAppRuntime.connect();
```

Behind the scenes:

1. Reads `wid` and `t` from the iframe URL `?wid=…&t=…`.
2. Sends a `window.hello` RPC over `postMessage` to the parent.
3. Receives `capabilities`, `view_meta`, `entry_payload`, `runtime_state`, `geometry` and resolves.
4. Starts a 10s heartbeat (`window.ready` after first hello, then `window.heartbeat`).
5. Subscribes to host events (`auth.refresh`, `entry_payload`, `runtime_state_synced`, `geometry_changed`, `close`, …) — `auth.refresh` is handled internally by replacing the bound token.

The returned object:

```ts
interface AnnaAppRuntime {
  windowUuid: string;
  appId:      string;
  versionId:  string;
  /** The app's own identity from the `hello` handshake (host >= dispatcher
   *  0.25.0; `null` on older hosts). `app.id` is the numeric AnnaApp.id —
   *  the exact value `open_app_view` prompts need. */
  app:        { id: number; slug?: string; name?: string } | null;
  viewMeta:   { name: string; title: string; default_size: {w,h}; … };
  capabilities: { host_api_version: string };   // no per-namespace scopes — every method is available

  /** Initial payload supplied by `open_app_view(payload=…)` */
  entryPayload: any;
  /** Server-persisted runtime_state from `storage.set` calls */
  runtimeState: Record<string, any>;
  /** Last known window geometry */
  geometry: { x: number; y: number; w: number; h: number; … };

  // Namespaced proxies — every method returns a Promise<RpcResponse>
  tools:    { list(): Promise<…>; invoke(args): Promise<…> };
  chat:     { append_artifact(args): Promise<…> /* …stubs… */ };
  storage:  { get(args): Promise<…>; set(args): Promise<…>; delete(args): Promise<…> };
  artifact: { /* stubs, see Host API */ };
  llm:      { /* stubs, see Host API */ };
  fs:       { /* stubs, see Host API */ };
  prefs:    { /* stubs, see Host API */ };
  window: {
    set_title({ title }):    Promise<…>;
    resize({ w, h }):        Promise<…>;
    focus():                 Promise<…>;
    close({ reason? }):      Promise<…>;
    open_view({ view, payload? }): Promise<…>;
    report_error({ message, stack? }): Promise<…>;
  };

  // Event subscription
  on(event:
       | "entry_payload"
       | "runtime_state_synced"
       | "geometry_changed"
       | "title_changed"
       | "close",
     handler: (payload: any) => void
    ): () => void;  // returns unsubscribe
}
```

Every namespace proxy covers the full Host API surface of the host you are running on (`window.hello` only reports `capabilities.host_api_version`; there are no per-namespace scopes). Every method is available to an installed App; the only refusals come from the manifest's [capability declarations](/developers/apps/app-manifest#capability-declarations): `permission_denied` for an undeclared `credentials` provider, an undeclared cross-app storage scope, or `tools.invoke` on an Executa outside `required_executas` / `optional_executas`, and `share_not_declared` / `conversation_not_declared` for `share.*` / `conversation.*` without their declaration — you cannot escalate from the client.

## Resume vs first open

The host calls your iframe with two bundles of state:

| Field | Source | Purpose |
|---|---|---|
| `entry_payload` | `open_app_view(payload=…)` and `update_app_view(runtime_state_patch=…)` | Per-call instructions from the LLM (or the user via the deck) |
| `runtime_state` | `storage.set` calls from prior sessions | Your own persisted UI state (≤256 KB total) |

Recommended pattern:

```js
const anna = await AnnaAppRuntime.connect();

if (anna.runtimeState?.bootedOnce) {
  // Resume: rebuild UI from runtime_state, then merge any new entry_payload
  hydrateFrom(anna.runtimeState);
  if (anna.entryPayload) applyAdditionalInstruction(anna.entryPayload);
} else {
  // First open: drive UI from entry_payload alone
  bootstrapFrom(anna.entryPayload);
  await anna.storage.set({ key: "bootedOnce", value: true });
}

anna.on("entry_payload", payload => {
  // LLM pushed new instructions via update_app_view
  applyAdditionalInstruction(payload);
});

anna.on("runtime_state_synced", state => {
  // Another tab/device updated runtime_state
  hydrateFrom(state);
});
```

## Storing state

`storage.set` writes into `anna_app_window_sessions.runtime_state` (JSON, max 256 KB). Use it as a tiny key-value store. For larger objects, persist them to your own backend or to an artifact and store only a handle in `runtime_state`.

```js
await anna.storage.set({ key: "draft", value: { title, body } });
const { value } = await anna.storage.get({ key: "draft" });
await anna.storage.delete({ key: "draft" });

// Enumerate keys (paginated, returns the APS list shape):
const { items, next_cursor } = await anna.storage.list({
  prefix: "draft/",
  limit: 100,
});
```

The host debounces the underlying disk write; concurrent calls are coalesced. On tab close the host page emits a `navigator.sendBeacon` flush to `POST /runtime/windows/{wid}/flush` so the latest state is durable even when the user just closes the tab.

## Calling Executas

```js
const { result } = await anna.tools.invoke({
  tool_id: "tool-yourhandle-browser-abcd1234",
  method:  "page.fetch",   // required when tool_id is mint-only (no fixed plugin namespace)
  args:    { url: "https://example.com" }
});
```

The host resolves the `tool_id` against `(plugin_name, tool_name)` from the Executa registry, then invokes the Executa over NATS on the user's currently-online Anna Agent. If no agent is online you get `agent_unavailable`.

Only the `tool_id`s in `required_executas` / `optional_executas` can be invoked, and the Executa must be installed and enabled for the user.

Required Executas are deployed and reachable by the time your bundle starts — the host [does not load the app](/developers/apps/app-manifest) until they are. Optional ones carry no such guarantee: `tools.invoke` can fail with `executa_not_deployed` (the platform is already deploying it) or `agent_waking` (the user's Cloud Agent is starting). Both are raised before the tool runs and carry `details.retriable: true`. The host retries once on its own; if the error still reaches you, back off and retry, and subscribe to `anna.tools.onChanged(cb)` to re-run `tools.list` when a deployment lands. A call to a required Executa can surface the same two errors when a running window loses its Agent for longer than the host holds the call.

## Title, resize, close

```js
await anna.window.set_title({ title: "Editing report.md" });
await anna.window.resize({ w: 1024, h: 768 });
await anna.window.close({ reason: "user_done" });
```

`window.*` needs nothing declared, like every other namespace.

## Follow the user's theme and language

The host tells your App which theme and UI language the user picked in Anna
(SDK ≥ 0.24.0). Both are read-only on the runtime and come with a subscription
that replays the current value once — so you never race the handshake and the
first paint is already right:

```js
const anna = await AnnaAppRuntime.connect();

anna.theme;      // 'light' | 'dark'
anna.themeMode;  // 'light' | 'dark' | 'system'
anna.locale;     // 'en' | 'zh-CN' | …

anna.onThemeChange(({ theme }) => { document.documentElement.dataset.theme = theme; });
anna.onLocaleChange(({ lang }) => setUiLanguage(lang));
```

Migration in three steps:

1. Apply the theme to `<html data-theme>` from `onThemeChange`.
2. Style with `:root[data-theme="light"]` / `:root[data-theme="dark"]`.
3. Keep `@media (prefers-color-scheme: dark) { :root:not([data-theme]) { … } }` as the
   standalone / older-host fallback — hosts that predate this contract send nothing,
   and the SDK then falls back to `prefers-color-scheme` / `navigator.language`.

These are one-way host → app broadcasts (`theme.changed`, `locale.changed`), not RPC
methods — nothing to declare.

## Durable conversations

`anna.conversation` (SDK ≥ 0.29.0) wraps the `conversation.*` namespace: long-lived
conversations with the user's memory, persisted history and full agent. It needs
`ui.host_api.conversation: true` in the manifest.

```js
const { conversations } = await anna.conversation.list();
const stream = anna.conversation.send({
  conversation_uuid: conversations.find((c) => c.is_default).uuid,
  message: "What did we decide yesterday?",
});
for await (const frame of stream) { /* render the reply as it streams */ }
```

`send` returns the stream synchronously; `stream.ready` resolves to `{ task_id, stream_id }`
once the run is queued. After a reload, `anna.conversation.status()` tells you whether a
run is still going and `anna.conversation.attach()` resumes it. Full guide:
[Durable conversations](/developers/apps/app-ui-conversation).

## Errors

Every RPC returns a Promise that resolves with a structured response:

```ts
{ ok: true,  result: any }
{ ok: false, error: { code: string; message: string; details?: any } }
```

Common codes:

| Code | Meaning |
|---|---|
| `invalid_token` | JWT expired or wrong window — the SDK auto-refreshes most cases |
| `permission_denied` | Undeclared `credentials` provider / storage scope, or `tool_id` not in `required_executas` / `optional_executas` |
| `invalid_arg` | Schema mismatch on RPC args |
| `not_found` | Window already closed; storage key missing; etc. |
| `agent_unavailable` | `tools.invoke` could not reach the user's Anna Agent |
| `executa_not_deployed` | `tools.invoke`: the Executa is not on the Agent yet; a deployment is under way. Retriable |
| `agent_waking` | `tools.invoke`: the user's Cloud Agent is still starting. Retriable |
| `bundle_not_ready` | (At `open_app_view` time) the version's bundle is still `draft` |
| `rate_limited` | Too many RPCs in flight |

Full namespace × method matrix and current implementation status: [App UI Host API](/developers/apps/app-ui-host-api).
