Download sdk/docs/two-layer.md from Anirudh1950/MentraOS: direct link, hf CLI and curl.
- Browser
- Download file 5.9 kB
-
https://huggingface.co/Anirudh1950/MentraOS/resolve/main/sdk/docs/two-layer.md
- Command line
-
hf download hf://Anirudh1950/MentraOS/sdk/docs/two-layer.md
-
curl -L -o two-layer.md https://huggingface.co/Anirudh1950/MentraOS/resolve/main/sdk/docs/two-layer.md
Two-layer miniapp architecture
This page documents the two-layer miniapp model. If you're writing a new miniapp, use this layout. The older single-bundle WebView pattern still works but is being phased out.
Why two layers
Each running miniapp had its own persistent WebKit/WebView process β ~80β150 MB per backgrounded miniapp. iPhone SE (3 GB RAM) jetsam'd within a second after about 10 of them were spawned. The fix:
- Background layer (always-on, no DOM) β a per-miniapp JS context on JavaScriptCore (iOS) / QuickJS via Zipline (Android). 0.75β5 MB per context. Owns all glasses logic.
- UI layer (on-demand, full DOM) β a fresh WebView spawned when the user opens the miniapp's settings; destroyed on exit. No persistent off-screen state. Standard React + Tailwind + DOM, but zero direct native access β talks to its own background layer through a typed message bus.
Background runtime contract
The background is not a browser and not Node. Do not rely on an API just
because TypeScript or Bun accepts it during a build. MentraOS explicitly
provides console, timers (setTimeout, setInterval, and
queueMicrotask), fetch, WebSocket, per-miniapp localStorage,
crypto.getRandomValues, crypto.randomUUID, TextEncoder, TextDecoder,
atob, btoa, and the SDK-supported AbortController subset.
It does not provide window, document, DOM elements, performance,
XMLHttpRequest, crypto.subtle, Node built-ins (fs, path, and so on),
process, or a runtime module resolver. Use Date.now() for elapsed time.
Keep session.* calls, hardware subscriptions, durable state, and work that
must survive UI closure in src/background/. Keep rendering, browser APIs,
and UI-only libraries in src/ui/. Pass serializable data between them over
the typed message bus.
File layout
my-miniapp/
βββ miniapp.json
βββ src/
β βββ background/ # JSContext entry β always running
β β βββ index.ts # exports init(session)
β β βββ controllers/ # optional β split logic here as it grows
β βββ ui/ # WebView entry β opens on demand
β β βββ index.html
β β βββ main.tsx # mounts <App/> inside <MentraProvider>
β β βββ App.tsx
β βββ shared/
β βββ channels.ts # typed channel registry β both sides import
β βββ types.ts # cross-boundary types
βββ dist/ # output of `bun run build`
βββ background/index.js
βββ ui/index.html + assets
miniapp.json declares both entries:
{
"packageName": "com.example.notes",
"version": "1.0.0",
"name": "Notes",
"type": "standard",
"sdkVersion": "0.3.0",
"minHostVersion": "1.42.0",
"entry": {
"background": "dist/background/index.js",
"ui": "dist/ui/index.html"
},
...
}
Sub-paths in @mentra/miniapp
The SDK ships two sub-paths under one package:
@mentra/miniapp/backgroundβMiniappSession+ everysession.*module type. Import this insrc/background/.@mentra/miniapp/uiβmentraglobal declaration + React adapters (MentraProvider,useSafeArea,useVisibility,MiniappHeader, ...). Import this insrc/ui/.
There is no bare @mentra/miniapp import. Sub-paths only. Picking the
wrong side fails at compile time β the mentra global isn't visible
from @mentra/miniapp/background, and MiniappSession isn't visible
from @mentra/miniapp/ui.
Typed channels
src/shared/channels.ts is the single source of truth for every
name + payload shape that crosses the WebView β background boundary.
import type {MentraTyped} from "@mentra/miniapp/ui"
export interface Channels {
// background β UI
"captions:snapshot": {history: string[]}
// UI β background
"captions:clear": Record<string, never>
}
declare global {
var mentra: MentraTyped<Channels>
}
Both halves of the build inline this file. There is no runtime registry β channel names are opaque strings on the wire and only enforced at compile time.
Build
bun run build
Produces dist/background/index.js and dist/ui/* in a single pass.
The CLI's mentra-miniapp pack zips both folders into one bundle.
Lifecycle
- Install β host downloads bundle, unzips, validates manifest,
spawns the JSContext, runs
init(session). Background is alive. - User opens UI tile β host creates a fresh WebView, injects the
mentrashim, loadsdist/ui/index.html. Once the app mounts,<MentraProvider>callsmentra.ready().session.ui.onOpenhandlers fire in background. - User navigates away β host destroys the WebView. JSContext
stays alive.
session.ui.onClosefires. - Disable / uninstall β host calls
session.onBeforeDisconnecthandlers, kills the JSContext. Bundle stays unless uninstalled.
Crash recovery
If background crashes, the host runs the controller's state machine:
- 1st crash β silent respawn after 2s
- 2nd within 5min β restart toast + 8s backoff
- 3rd β 30s backoff
- 4th β CRASHLOOP_DISABLED banner (user "Try again" tap re-enables)
A clean 60s window in RUNNING resets the retry counter.
See also
- session.ui β the background-side message bus reference.
- agents/mentrajs-two-layer-miniapp-architecture.md β full architecture spec, including memory profile and engine choice.
- The example miniapp (
examples/miniapp/) β canonical implementation following Appendix A of the architecture spec.