MentraOS / mobile /modules /engine /README.md
Anirudh1950's picture
Add files using upload-large-folder tool
b450976 verified
|
Raw History Blame Contribute Delete
14.5 kB
# @mentra/engine
Mentra Engine β€” the on-device miniapp library.
## Installation
```sh
npm install @mentra/engine
```
> **Peer packages:** the engine's `@mentra/*` peer dependencies (`crust`,
> `cloud-client`, `cloud-protocol`, `miniapp`) must be available to your
> package manager. Until every peer is published to npm, consume the engine
> from this monorepo's workspace (as the example OEM app does).
> **Secure storage:** `expo-secure-store` (`~55.0.14`) is a required peer
> dependency. The engine keeps Core sign-in credentials in it (iOS Keychain,
> Android Keystore) instead of in MMKV, and moves existing ones on first
> launch. Install it in your app like the other Expo peers.
> **Module format:** the published entry points target **React Native /
> Metro** consumers (the `react-native` exports condition). Loading
> `@mentra/engine` from plain Node (`require`/ESM) is not supported at 0.1.x β€”
> the `default` condition's build output is ESM with extensionless imports and
> will not resolve under Node's loader.
## Entry points
The package exposes its Engine entry points and a supported Bluetooth SDK
facade (declared in `package.json` `exports`,
with the `react-native` condition pointing at `src/` so Metro, tsc and jest
resolve live TypeScript source):
- **`@mentra/engine`** (main, `src/index.ts`) β€” the OEM-facing surface: the
`engine` namespace (`configure`/`start`/`stop` + typed domain facades),
contract/read-model types, and pure helpers host UI renders with
(`decideReconnect`, `deriveDisplayState`, the `useApps`-style hooks,
OTA policy constants, hardware capability tables, `BgTimer`). Judgment rule:
read models, commands, pure functions and types are main; anything that
mutates runtime state or exposes a store/service is not.
- **`@mentra/engine/ota`** (`src/react/index.ts`) β€” the complete Mentra Live OTA
controller plus its stock full-screen renderer. `useMentraLiveOta` owns the
check, hotspot or Wi-Fi install, APK/MTK/BES progress, reboot, retry, and final
verification behavior. `MentraLiveOtaFlow` renders that same public hook.
- **`@mentra/engine/bluetooth-sdk`** (`src/bluetooth-sdk/index.ts`) β€” the
complete public Bluetooth SDK surface, re-exported without a wrapper so it
has the same singleton identity as `@mentra/bluetooth-sdk`. The supported
SDK `react`, `types`, `photo-receiver`, `ota-transport`, and `debug` subpaths are mirrored
below this path. The SDK's `internal` entrypoint is deliberately not exposed.
See `cloud-v2/docs/issues/020-glasses-status-boundary/integration-review.md`
Β§D for the burn-down plan.
This module owns the pieces of miniapp logic and handling that aren't tied to
the rest of the manager app: the WebView message bus, the in-memory running
registry, and the JS globals that we inject into every miniapp WebView.
The goal is for all miniapp logic to live here over time. Today the move is
incremental β€” only the self-contained services have moved. Cross-cutting
services (LocalMiniappRuntime, MantleManager, Composer install pipeline) still
live under `mobile/src/` because they reach back into the manager's stores and
sockets.
## Public surface
```ts
import {engine, decideDevLaunchRoute} from "@mentra/engine"
import BluetoothSdk from "@mentra/engine/bluetooth-sdk"
```
- `decideDevLaunchRoute` β€” pre-flight a dev URL's `miniapp.json` to decide
whether to mount live or take the user to the offline screen.
### Mentra Live OTA flow
Bluetooth-only hosts can render the OTA flow without configuring or starting
the authenticated cloud connection or miniapp runtime:
```tsx
import {MentraLiveOtaFlow} from "@mentra/engine/ota"
;<MentraLiveOtaFlow onFinished={() => setShowOta(false)} onOpenWifiSetup={() => setShowWifiSetup(true)} />
```
The component starts only the glasses-status and OTA projections. A host that
already called `engine.start()` should pass `initializeRuntime={false}`. Show
the flow after a Mentra Live connects. Hosts must provide `onOpenWifiSetup`;
the flow invokes it only for older glasses that cannot provide the OTA hotspot
transport.
Apps that need different pages can render the same controller directly:
```tsx
import {useMentraLiveOta} from "@mentra/engine/ota"
const ota = useMentraLiveOta({onFinished, onOpenWifiSetup})
// Render ota.state.screen and invoke ota.install(), retryInstall(), finish(), etc.
```
On `up_to_date`, use `ota.state.completedUpdate` to distinguish a completed
update session from a standalone check. `releaseTransition` is optional release
metadata and is not a completion marker.
Customize presentation only. Engine must remain responsible for OTA ordering,
hotspot staging, restart recovery, retries, and verification. The canonical
stock and custom integration guide is
[Update Mentra Live](https://docs.mentraglass.com/bluetooth-sdk/software-update).
Released Engine packages contain a literal immutable OTA manifest URL and
SHA-256 generated by coordinated release CI. Modern-glasses manifest selection
is developer override, host-app release pin, then Engine release pin. It does
not derive a URL from the Bluetooth SDK version or fall through to a
glasses-reported or mutable production URL. An unpinned source build has OTA
disabled unless an Expo/React Native host explicitly sets
`EXPO_PUBLIC_ASG_OTA_VERSION_URL`; native source hosts use the Bluetooth SDK's
debug `setOtaVersionUrl` surface. Pre-39 glasses retain their separate legacy
path because those clients ignore the URL sent by the phone.
## Incident reports and collection completion
`submitIncidentReport(event)` is the shared Promise entrypoint for Android intent
and Mac app incident requests. It files once, submits phone diagnostics, asks the
paired Mentra Live for ASG/BES logs, then waits for their Core storage receipts
before returning the final `INCIDENT_REPORT_RESULT`. The testing framework awaits
that receipt before ordinary teardown; it does not need report-reader credentials.
The Promise resolves only when every required log source is `received` with a stored
artifact ID. Without a paired Mentra Live, only phone logs are required. Requirements
are captured before submission; a subsequent disconnect does not drop glasses logs.
A source failure, unavailability or the 20-second collection deadline rejects with
`IncidentReportError.result`, retaining the created report ID and partial receipts.
The host catches that error to show the failed receipt; the testing framework records
it and continues every teardown step and the next independent test. It never re-files
the incident or changes the original test failure. Cloud and miniapp server
collection continue independently because they do not need a live glasses connection.
Automated requests (`source: "mentra_automated_testing"`) require valid `alert_id`
and `test_run_id`. The engine sends their exact typed
`automationCorrelation: {alertId, testRunId}` with report creation, so Core stores
the binding before collection finishes. Existing authenticated run completion can
return `deviceIncident: {reportId, correlation}` after reading the unique,
hash-verified `incident-report/request.json` asset. This is a report link, even
when the native transport lost its final receipt or collection failed; it never
changes the original failed result or asserts successful uploads. Core refuses
duplicate bindings across reports or accounts. No worker report-reader credential
or repeated incident intent is needed. Older reports without this structured
binding cannot be recovered through this path.
`engine.reports.submit` creates a report and starts collection. Feedback uses this
surface without waiting for glasses uploads. Hosts needing completion can await the
separate storage receipt, whose failure rejects with `ReportCollectionError.collection`:
```ts
const submitted = await engine.reports.submit(report)
if (submitted.status === "submitted") {
const collection = await engine.reports.waitForCollection(submitted.reportId, {
sources: ["phone", "glasses", "glasses_firmware"],
timeoutMs: 20_000,
})
}
```
Bluetooth owns command delivery; Engine owns submission and collection completion;
Core owns artifact storage and source receipts. Readiness of a report is separate
from receipt of every log source.
## Imports
Inside `mobile/modules/engine/src/`, use **relative paths** (`./services/...`,
`../utils/...`). The mobile app's `@/*` alias is not configured here β€” there
is no build-time path rewriter for this module.
## Testing
Run the suite with `bun run test` (from this directory). It executes
`scripts/test.sh`, which runs **each test file in its own bun process** β€” do
not replace it with a single `bun test src`.
Why: bun's `mock.module` patches one process-wide module registry with live
ESM bindings, last write wins. Several suites mock the same specifiers
(`"@mentra/bluetooth-sdk/internal"` alone is mocked by `audioTestMocks.ts`,
`PhonePhotoCoordinator.test.ts`, and others), so in a shared process one
file's mock clobbers another's and suites that pass alone fail in the
combined run. Per-file processes give every suite an isolated registry.
The same rule applies when writing tests: it is fine to `mock.module` any
specifier your suite needs, but never rely on a mock installed by a
_different_ test file β€” each file must set up everything it imports.
## Phone notification presentation
`engine.phoneNotifications` owns native-notification configuration alongside the existing Android listener kill switch and per-app blocklist. Capture remains independent of presentation. A host starts/stops its presentation owner with `setPresentationActive(boolean)`; the Mentra App uses Notify's running state on both platforms.
- `nativeCapabilities()` distinguishes native presentation, phone content access, app filtering, and removal support.
- `nativeStatus()` / `onNativeStatus(listener)` expose native availability, authorization, desired controls, and failures.
- `usesNativePresentation()` selects firmware presentation. A host forwards its captured event through `presentNative(event)` and skips its local card for that event. This does not replace permission-gated miniapp forwarding.
- `onNativeDelivery(listener)` exposes Android transfer outcomes without message content.
Settings are `native_notifications_enabled`, `native_notifications_auto_display`, `native_notifications_duration`, and `native_notifications_do_not_disturb`. Native presentation defaults off. The Android `notifications_blocklist` is also passed to native configuration so pending work is invalidated when filtering changes. Disconnected events are not retained for replay.
On iOS, G2 receives ANCS directly; the host does not upload the app-identity relay back to the glasses. Full title/body access, editing the firmware app filter, and phone-dismissal synchronization remain unsupported. The existing G2 app-identity event is not evidence of full content access.
### Passive app permission diagnostics
`engine.permissions.status()` reads the current iOS app's Camera, Microphone,
Bluetooth and foreground Location authorization without requesting consent.
Location Services enablement is a separate field: an authorized app cannot use
Location when the global service is off. Local Network remains `unknown` because
iOS provides no passive authorization getter. Missing native implementations
reject as unavailable; they do not manufacture a grant.
Commissioning can send `com.mentra://test/permissions?request_id=<nonce>` to the
already selected app. It preserves the current screen and writes one atomic
receipt to the app container's `Library/Caches/MentraDiagnostics/permission-status.json`.
The receipt includes its request ID, observation time and the app's native
PID/UID, bundle paths and version. The host must verify that identity against the
same live selected process and installed artifact, and reject stale or mismatched
receipts. Status observation is separate from explicit permission requests and
never files an incident, starts recording, scans Bluetooth or joins a network.
An attended operator may separately send
`com.mentra://test/request-permissions?request_id=<batch>&readback_id=<fresh-nonce>&features=camera,microphone,location,bluetooth&timeout_ms=125000`
to the already selected, foregrounded Mentra App through the owning framework's
verified original-PID/lifetime URL carrier. A bare `open` or default scheme handler
can target another installed build and is not a commissioning entrypoint.
The caller owns the normal app reservation and must
show the person which selected recipient and permissions are about to be requested.
The app validates distinct bounded IDs, a nonempty unique subset of those four
features and a 1–125 second budget. It records the initial raw snapshot under the
batch ID, observes before each request, and uses `engine.permissions.request`
exactly once for each selected `notDetermined` permission. It does not record
media, scan for glasses, associate a network, click a system dialog or open Settings.
Existing grants, denial, restriction, disabled Location Services and unknown status
remain observed facts; independent eligible requests continue. Local Network has
no generic native grant getter or request here and remains `unknown`.
On settlement within the budget, the fixed native receipt is refreshed with the
separate readback nonce and actual grant states. A successful command does not
mean every grant was approved: the operator must inspect that raw receipt and
report missing permissions, including the exact app Settings/global Location
Services or system restriction action. Logs retain a bounded per-feature request
summary. A deadline rejects without claiming native cancellation; an outstanding
native consent request keeps the app's single-batch gate until it settles and
cannot be followed by another batch or further prompts. A raw receipt alone never
proves native writer cessation. Reconcile the original operation before cleanup;
use the existing passive nonce route to observe a later decision. If the app
leaves the foreground, no further requests start. None of this changes the passive
`/test/permissions` route or makes ordinary routine startup request consent.