# Two-layer architecture

> How a miniapp's always-on background and on-demand UI layers work and talk to each other.

Source: https://docs.glassly.ai/app-devs/core-concepts/two-layer-architecture/

Every Glassly miniapp has two layers. Understanding the split is the key to the
whole SDK: it determines where your code runs, what it can reach, and how the
two halves communicate.

| Layer | Lifetime | Has DOM? | Hardware access | Import from |
|---|---|---|---|---|
| **Background** | Always on while the miniapp is enabled | No | Full: owns the `session` | `@glassly/miniapp/background` |
| **UI** | Only while the user has your tile open | Yes (React) | None: talks to background | `@glassly/miniapp/ui`, `@glassly/miniapp/react` |

## File layout

```
my-miniapp/
├── miniapp.json              # declares both entry points
├── build.ts                  # bundles both layers in one pass
└── src/
    ├── background/
    │   └── index.ts          # registerMiniapp(session => …)
    ├── ui/
    │   ├── index.html
    │   ├── main.tsx          # mounts <App/>, calls glassly.ready()
    │   └── App.tsx
    └── shared/
        └── channels.ts       # typed channel registry: both sides import it
```

`miniapp.json` points at the built output of each layer:

```json
{
  "entry": {
    "background": "background/index.js",
    "ui": "ui/index.html"
  }
}
```

## The background layer

The host evaluates your background bundle inside a per-miniapp JavaScript context
and calls your `registerMiniapp` handler once the connection is ready. This is
where every `session.*` call lives.

```typescript src/background/index.ts
import { registerMiniapp } from "@glassly/miniapp/background";
import "../shared/channels";

registerMiniapp(async (session) => {
  // Subscribe to glasses events here. The runtime tears them down on disable.
  session.transcription.on((data) => {
    session.display.render([
      { type: "text", id: "caption", box: { x: 0, y: 0, w: 576, h: 288 }, text: data.text },
    ]);
  });
});
```

The background runs **even when no UI is open**. Register your subscriptions in
the handler; they live for as long as the miniapp is enabled.

The background context is not a browser and not Node: it's a bare JS engine
(JavaScriptCore on iOS, QuickJS on Android). There's no `window`, no DOM, and no
module resolver at runtime, which is why `build.ts` bundles the SDK *into* your
background output rather than leaving it external.

### Background runtime APIs

Do not infer background support from what TypeScript or Bun accepts at build
time. The background bundle targets a small, cross-platform runtime. Glassly
currently provides these browser-like globals:

| Available | Scope and limits |
|---|---|
| `console` | `log`, `info`, `warn`, `error`, `debug`, and `trace` |
| Timers | `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`, and `queueMicrotask` |
| `fetch` | String, `ArrayBuffer`, typed-array, and `DataView` request bodies; `text()`, `json()`, and `arrayBuffer()` response helpers over the native HTTP bridge |
| `WebSocket` | Native WebSocket bridge |
| `localStorage` | Per-miniapp string key/value storage |
| `crypto` | `getRandomValues` and `randomUUID`; `crypto.subtle` is not implemented |
| Encoding | `TextEncoder`, `TextDecoder`, `atob`, and `btoa` |
| Cancellation | The SDK-supported `AbortController` / `AbortSignal` subset |

Empty string and zero-length binary bodies are preserved on iOS and Android.
Array views send only their selected byte range. For a binary upload:

```ts
await fetch("https://api.example.com/upload", {
  method: "POST",
  headers: {"Content-Type": "application/octet-stream"},
  body: new Uint8Array([0x01, 0x02, 0x03]),
});
```

Common browser and Node APIs are **not** available in the background, and the
build rejects them by name with the source location and a supported alternative:

| Global | Use instead |
|---|---|
| `window`, `document`, `HTMLElement`, `customElements`, `MutationObserver` | Move the DOM work to `src/ui/`. |
| `navigator` | Move browser capability checks to `src/ui/`. |
| `location` | `session.location` for glasses/phone position; move browser URL work to `src/ui/`. |
| `performance` | `Date.now()` for elapsed time. |
| `XMLHttpRequest`, `EventSource` | `fetch()` (or `WebSocket` for `EventSource`). |
| `Request`, `Response`, `Headers` | Call `fetch()` with a URL string and options, and consume what it returns. |
| `URL`, `URLSearchParams` | Pass URL strings directly and build query strings explicitly. |
| `FormData` | Encode the body as a string or bytes and set the matching `Content-Type`. |
| `Blob`, `File`, `FileReader` | `session.blob` for binary storage; browser file handling goes in `src/ui/`. |
| `indexedDB`, `caches` | `session.storage`, `session.blob`, or `localStorage`. |
| `Worker`, `MessageChannel` | Keep durable work in the background entry; use `session.ui` channels to talk to the UI. |
| `process`, `Buffer` | `Uint8Array` plus `TextEncoder`/`TextDecoder` or the SDK base64 helpers. Only `PUBLIC_*` values are inlined at build time. |
| `require`, `module`, `exports`, `__dirname`, `__filename` | Static ES module imports Bun can bundle; don't read the filesystem at runtime. |

Node built-ins (`fs`, `path`, `child_process`, and the rest) are rejected the
same way. Put rendering, DOM work, and browser UI libraries in `src/ui/`. Put
`session.*` calls, hardware subscriptions, durable state, and logic that must
continue after the UI closes in `src/background/`. Exchange only serializable
data through `glassly.*` / `session.ui.*`.

`location` and `Blob` are the two that surprise people: in the background
`session.location` is the GPS module, not the browser URL object, and binary
data belongs in `session.blob`.

If an AI coding agent introduces `performance.now()`, DOM access, or a Node API
under `src/background/`, move that code to the UI or replace it with a supported
primitive. For elapsed time in the background, use `Date.now()`.

Projects created with `@glassly/create-miniapp` also check background source and
its imported shared files during `bun run build`. Common unsupported browser or
Node APIs fail the build with the source location and a supported alternative.

## The UI layer

The UI is a normal React app. It has **zero** direct native access: it reaches
the glasses only by sending messages to its own background layer. It mounts
inside `<MiniappProvider>` and must call `glassly.ready()` on boot so the host
knows it's mounted.

```tsx src/ui/main.tsx
import { createRoot } from "react-dom/client";
import { MiniappProvider } from "@glassly/miniapp/ui";
import { App } from "./App";

createRoot(document.getElementById("root")!).render(
  <MiniappProvider>
    <App />
  </MiniappProvider>,
);

glassly.ready(); // flush any buffered messages from background
```

## Talking between layers

The two layers never share memory: they pass messages over a typed bus. You
declare every channel once in `src/shared/channels.ts`; both halves import it, so
names and payload shapes are enforced at compile time.

```typescript src/shared/channels.ts
import type { TypedUiGlobal } from "@glassly/miniapp/ui";

export interface Channels {
  ping: { at: number };                        // UI → background
  pong: { at: number; roundtripMs: number };   // background → UI
}

declare global {
  var glassly: TypedUiGlobal<Channels>;
}
```

**From the UI**, use the injected `glassly` global:

```tsx
glassly.send("ping", { at: Date.now() });            // fire-and-forget
glassly.on("pong", ({ roundtripMs }) => { /* … */ }); // subscribe
const res = await glassly.request("getNotes", {});    // request/response (RPC)
```

**From the background**, use `session.ui`:

```typescript
session.ui.onOpen(() => session.ui.send("pong", { at: Date.now(), roundtripMs: 0 }));
session.ui.on("ping", ({ at }) => { /* … */ });
session.ui.handle("getNotes", async () => ({ notes }));  // respond to glassly.request
```

The two sides are intentionally asymmetric: `glassly.send` from the UI **buffers**
until the WebView calls `ready()`, while `session.ui.send` from the background
**drops silently** when no WebView is open (there's no one to receive it).

There's no runtime channel registry: channel names are opaque strings on the
wire, validated only by TypeScript. See
[Interop & Actions](https://docs.glassly.ai/app-devs/core-concepts/miniapp-interop.md) for the separate,
cross-miniapp RPC layer (`session.actions`).

## Lifecycle

1. Start: after installation, opening the miniapp, an Always On autostart, or
   an authorized background start spawns the background JS context and runs
   your `registerMiniapp` handler.
2. UI opens: the user taps your tile; the host spawns a WebView, injects the
   `glassly` shim, and loads `ui/index.html`. The WebView calls `glassly.ready()`,
   and `session.ui.onOpen` fires in the background.
3. UI closes: the user navigates away; the host destroys the WebView. The
   background context stays alive and `session.ui.onClose` fires.
4. Stop / uninstall: the host tears down your subscriptions and kills the
   background context.

Manifest [`alwaysOn: true`](https://docs.glassly.ai/app-devs/core-concepts/miniapp-manifest.md#always-on-miniapps)
starts the miniapp at host launch and keeps its background alive when its app
switcher card is dismissed. The wearer can override the default or explicitly
stop it from the switcher's Always On controls. For ordinary
miniapps, dismissing the switcher card stops the miniapp, and only Always On
miniapps start at launch: one that was running when the Glassly App closed
stays stopped until the wearer opens it again. Keep durable state in storage so
it can be restored on the next start.

## Crash recovery

If your background layer crashes, the host restarts it automatically. Repeated
crashes back off and eventually show the user a "try again" prompt, so aim to
reach a stable state quickly on startup.

## Next steps

- [The manifest](https://docs.glassly.ai/app-devs/core-concepts/miniapp-manifest.md)
Declare entries, permissions, and hardware in `miniapp.json`.
- [The session](https://docs.glassly.ai/app-devs/core-concepts/session.md)
The background-side handle to every glasses capability.
- [The UI layer](https://docs.glassly.ai/app-devs/core-concepts/webviews/react-webviews.md)
React hooks, the capsule menu, and safe areas.
- [Interop & Actions](https://docs.glassly.ai/app-devs/core-concepts/miniapp-interop.md)
Let other miniapps (and Glassly AI) call yours.
