Download mobile/modules/engine/src/services/MiniappLauncher.ts from Anirudh1950/MentraOS: direct link, hf CLI and curl.
- Browser
- Download file 36.4 kB
-
https://huggingface.co/Anirudh1950/MentraOS/resolve/main/mobile/modules/engine/src/services/MiniappLauncher.ts
- Command line
-
hf download hf://Anirudh1950/MentraOS/mobile/modules/engine/src/services/MiniappLauncher.ts
-
curl -L -o MiniappLauncher.ts https://huggingface.co/Anirudh1950/MentraOS/resolve/main/mobile/modules/engine/src/services/MiniappLauncher.ts
36.4 kB
| /** | |
| * MiniappLauncher β headless launch/teardown of a local miniapp's background | |
| * JS context. | |
| * | |
| * This is the one piece of "run a miniapp" that used to live inside the | |
| * `LocalMiniappView` React component (resolve the bundle β read the manifest β | |
| * `spawnAndRegister`), triggered only when the Compositor mounted that | |
| * component on foreground. Pulling it into the runtime means: | |
| * | |
| * - `start()` can actually spawn an app even when nothing foregrounds it | |
| * (e.g. a system app launching another miniapp via `session.miniapps`). | |
| * - the action broker can wake a stopped target headlessly β no UI at all. | |
| * - the dev hot-reload respawn path and the WebView mount path share one | |
| * resolve+spawn recipe instead of three copies. | |
| * | |
| * The launcher is **headless**: no React, no RN components. The engine-owned | |
| * MiniappEngine hands it the {@link MentraJSRouter} instance once during | |
| * engine construction. OEMs embedding the runtime drive miniapp lifecycle | |
| * through the engine facade and stores, not a separate launcher configure API. | |
| * | |
| * Boundary: the launcher owns the **background** context. WebView *rendering* | |
| * (the UI layer) stays with the host β the launcher just hands back the | |
| * resolved UI entry so the host can mount its `<WebView>`. | |
| * | |
| * Fleet: every path that makes a local miniapp execute as user activity comes | |
| * through here, so the launcher reports each such launch (and each that fails | |
| * once past the availability gate) β a restore, a miniapp started by another | |
| * miniapp or an action, a screen opened directly, a restart after a reinstall. | |
| * A launch the apps store's `start` makes is reported by `start` itself | |
| * (`fleetEvents.claimLaunch`); a context already executing, or one a hidden | |
| * action wake keeps out of the running tray, is no launch. | |
| * | |
| * Age ratings: every launch path comes through here, so this is where a miniapp rated above the host app's own | |
| * rating meets the age gate as it opens, whether it was installed with the sheet or headlessly (a Fleet assignment, | |
| * a system miniapp). A launch the person makes in front of the app may ask their age once; any other launch needs it | |
| * declared already. | |
| */ | |
| import type {FleetLaunchFailureReason} from "@mentra/cloud-protocol" | |
| import {File} from "expo-file-system" | |
| import {AppState, Platform} from "react-native" | |
| import { | |
| getConfigValues, | |
| isDevMiniappAllowed, | |
| isMiniappAvailable, | |
| type MiniappAvailabilityMode, | |
| } from "../runtime/bootstrap" | |
| import {resolveDevBundleSource} from "../utils/devMiniappSnapshot" | |
| import {storage} from "../utils/storage/storage" | |
| import {MiniappRunningError} from "../utils/storeInstallRuntime" | |
| import appRegistry, {getLocalAppRunningState, saveLocalAppRunningState} from "./AppRegistry" | |
| import devServerBridge from "./DevServerBridge" | |
| import {fleetEvents} from "./fleet/fleetEvents" | |
| import localMiniappRuntime, {type InstalledMiniappManifest} from "./LocalMiniappRuntime" | |
| import {checkManifestVersions} from "./manifestVersionGate" | |
| import type {MentraJSRouter} from "./MentraJSRouter" | |
| import {checkMiniappAge, type AgeGateVerdict, type AgeRatedMiniapp} from "./miniappAgeGate" | |
| import {developmentOriginName, miniappOrigin, miniappOriginUrl, type MiniappOriginPlatform} from "./miniappOrigin" | |
| import {isHostTrustedSystemMiniapp} from "./SystemMiniappPolicy" | |
| /** The miniapp's server no longer admits this account (Fleet revocation): it cannot launch until access returns. */ | |
| export class MiniappAccessRevokedError extends Error { | |
| constructor(readonly packageName: string) { | |
| super(`MiniappLauncher: access to ${packageName} was revoked`) | |
| this.name = "MiniappAccessRevokedError" | |
| } | |
| } | |
| /** | |
| * The miniapp is rated above the host app's own rating and the person's declared age doesn't let it open (see | |
| * {@link AgeGateVerdict}). A person opening it in front of the app was asked their age, or told why. | |
| */ | |
| export class MiniappAgeRestrictedError extends Error { | |
| constructor( | |
| readonly packageName: string, | |
| readonly verdict: Exclude<AgeGateVerdict, "allowed">, | |
| ) { | |
| super(`MiniappLauncher: ${packageName} is age-rated and did not open (${verdict})`) | |
| this.name = "MiniappAgeRestrictedError" | |
| } | |
| } | |
| /** | |
| * The bundle needs a newer Mentra App, or a Mentra Miniapp SDK this one doesn't run: the rule installs refuse by, | |
| * checked again as it launches. A release a newer Mentra App installed stays on disk when an older one replaces it (a | |
| * development build replaced from TestFlight), and would otherwise start against features this one lacks. The message | |
| * is for logs; a screen explains it in the person's language, as an install refused by the same rule does. | |
| */ | |
| export class MiniappIncompatibleHostError extends Error { | |
| constructor( | |
| readonly packageName: string, | |
| readonly miniappName: string, | |
| readonly reason: string, | |
| ) { | |
| super(`${miniappName} can't run on this phone: ${reason}`) | |
| this.name = "MiniappIncompatibleHostError" | |
| } | |
| } | |
| interface LauncherDeps { | |
| /** The host-constructed router (needs the native Crust binding). */ | |
| router: MentraJSRouter | |
| } | |
| /** Hints the host may pass from a view's props to avoid re-deriving them. */ | |
| export interface LaunchHints { | |
| devUrl?: string | |
| /** Retained for caller compatibility; released launches use the committed active version. */ | |
| version?: string | |
| devPort?: string | |
| } | |
| export interface RuntimeLaunchOptions { | |
| /** False for an invocation-scoped wake that must not enter the running tray. */ | |
| projectRunning?: boolean | |
| /** | |
| * Who started the miniapp, for the Fleet launch this call makes, if it makes one: the person (a screen they opened) | |
| * or the platform (a restore, another miniapp, a restart). Defaults to automatic. | |
| */ | |
| trigger?: "user" | "automatic" | |
| } | |
| function availabilityMode(options?: RuntimeLaunchOptions): MiniappAvailabilityMode { | |
| return options?.projectRunning === false ? "background" : "interactive" | |
| } | |
| /** Everything the launcher resolved for a package β bg source + UI entry. */ | |
| export interface ResolvedBundle { | |
| bgSource: string | |
| /** Where the screen loads from. See {@link LaunchResult.uiUri}. */ | |
| uiUri: string | null | |
| /** The origin `uiUri` belongs to. See {@link LaunchResult.uiOrigin}. */ | |
| uiOrigin: string | null | |
| /** The bundle root the package's origin serves. See {@link LaunchResult.uiRootDir}. */ | |
| uiRootDir: string | null | |
| /** The name the origin is for. See {@link LaunchResult.uiOriginName}. */ | |
| uiOriginName: string | null | |
| /** A development build: a live development server or a development snapshot. */ | |
| devBuild: boolean | |
| declaredPermissions: string[] | |
| installedManifest?: InstalledMiniappManifest | |
| /** What the bundle's `miniapp.json` declares as `ageRating`; null when it declares none. */ | |
| ageRating: unknown | |
| /** Build-owned SYSTEM trust derived from install provenance, never the manifest. */ | |
| hostTrustedSystem: boolean | |
| /** Set for dev miniapps (HTTP off the dev server); null for released. */ | |
| devUrl: string | null | |
| devPort: number | null | |
| } | |
| /** What the host needs back to render the UI layer. */ | |
| export interface LaunchResult { | |
| /** | |
| * Where the screen loads from. An installed release loads from its | |
| * package's own origin: `miniapp://<packageName>/<ui entry>` on iOS and | |
| * `https://<host>.miniapp.invalid/<ui entry>` on Android (see | |
| * {@link miniappOriginUrl}), a development snapshot from the origin of its | |
| * {@link uiOriginName}. A live development build loads from its development | |
| * server. Null when there is no screen to load. | |
| */ | |
| uiUri: string | null | |
| /** The origin `uiUri` belongs to, for the WebView's `originWhitelist`. */ | |
| uiOrigin: string | null | |
| /** | |
| * The root of the active version's bundle, which the package's origin | |
| * serves (the WebView's `miniappOrigin.rootDir`). Null when the screen loads | |
| * from a development server. | |
| */ | |
| uiRootDir: string | null | |
| /** | |
| * The name the origin serves `uiRootDir` under (the WebView's | |
| * `miniappOrigin.packageName`): the package name for a release, and | |
| * {@link developmentOriginName} for a development snapshot, so a development | |
| * build never shares web storage with a release of its name. Null with | |
| * `uiRootDir`. | |
| */ | |
| uiOriginName: string | null | |
| /** A development build: a live development server or a development snapshot. */ | |
| devBuild: boolean | |
| } | |
| const NO_UI: LaunchResult = {uiUri: null, uiOrigin: null, uiRootDir: null, uiOriginName: null, devBuild: false} | |
| function launchResultOf(resolved: ResolvedBundle | null | undefined): LaunchResult { | |
| if (!resolved) return NO_UI | |
| return { | |
| uiUri: resolved.uiUri, | |
| uiOrigin: resolved.uiOrigin, | |
| uiRootDir: resolved.uiRootDir, | |
| uiOriginName: resolved.uiOriginName, | |
| devBuild: resolved.devBuild, | |
| } | |
| } | |
| /** The platform whose origin shape the Mentra App's WebView serves. */ | |
| function originPlatform(): MiniappOriginPlatform { | |
| return Platform.OS === "android" ? "android" : "ios" | |
| } | |
| /** `scheme://host[:port]` of an http(s) URL, lowercased as a page's `location.origin` reads it. */ | |
| function serverOrigin(url: string): string | null { | |
| const match = /^(https?:\/\/[^/?#]+)/i.exec(url) | |
| return match ? match[1].toLowerCase() : null | |
| } | |
| /** | |
| * Why a launch failed, as the code Fleet takes (Phase 12): never the error's text. A bundle that cannot be found is | |
| * `bundle_missing`; one that needs a newer Mentra App `incompatible_host`; a deployment, age or access block | |
| * `policy_blocked`; a context that did not start `spawn_failed`. | |
| */ | |
| export function launchFailureReason(error: unknown): FleetLaunchFailureReason { | |
| if (error instanceof MiniappIncompatibleHostError) return "incompatible_host" | |
| if (error instanceof MiniappAgeRestrictedError || error instanceof MiniappAccessRevokedError) return "policy_blocked" | |
| const message = error instanceof Error ? error.message : "" | |
| if (message.includes("cannot resolve bundle")) return "bundle_missing" | |
| if (message.includes("by deployment policy")) return "policy_blocked" | |
| if (message.includes("spawn failed")) return "spawn_failed" | |
| return "unknown" | |
| } | |
| class MiniappLauncher { | |
| private deps: LauncherDeps | null = null | |
| /** | |
| * In-flight launches keyed by packageName. Both apps.ts start() and the | |
| * WebView mount call ensureRunning() before the first spawnAndRegister | |
| * resolves β without this, neither sees the package in registeredPackages() | |
| * yet and both spawn the same context (a clobber/double-spawn). Concurrent | |
| * callers share the same promise. | |
| */ | |
| private readonly inFlight = new Map<string, Promise<LaunchResult>>() | |
| /** In-flight launches that keep their context out of the running tray (a hidden action wake). */ | |
| private readonly hiddenInFlight = new Set<string>() | |
| /** | |
| * Installs hold new launches of their package until they commit or roll | |
| * back: explicit installs for the whole install, automatic updates only while | |
| * their files change. | |
| */ | |
| private readonly installing = new Map<string, Promise<void>>() | |
| /** | |
| * Run an automatic update only while the miniapp is idle. `install` prepares | |
| * the release, then calls `beforeActivate` immediately before files change: | |
| * a launch during preparation wins and the update defers with | |
| * {@link MiniappRunningError}; a launch during activation waits for the | |
| * commit or rollback and then reads the resulting bundle. | |
| */ | |
| async installWhenIdle<T>(packageName: string, install: (beforeActivate: () => void) => Promise<T>): Promise<T> { | |
| const assertIdle = () => { | |
| if (this.isRunning(packageName) || this.inFlight.has(packageName)) throw new MiniappRunningError(packageName) | |
| } | |
| assertIdle() | |
| let release: (() => void) | undefined | |
| try { | |
| return await install(() => { | |
| assertIdle() | |
| release = this.reserveInstall(packageName) | |
| }) | |
| } finally { | |
| release?.() | |
| } | |
| } | |
| /** Stabilize existing launches and hold new ones until an explicit install finishes. */ | |
| async pauseLaunches(packageName: string): Promise<() => void> { | |
| const release = this.reserveInstall(packageName) | |
| // Launches already resolving a bundle must settle before the installer | |
| // decides whether a context needs stopping/restarting. A failed launch is also settled. | |
| await this.inFlight.get(packageName)?.catch(() => {}) | |
| return release | |
| } | |
| private reserveInstall(packageName: string): () => void { | |
| if (this.installing.has(packageName)) throw new Error(`An install is already activating ${packageName}`) | |
| let resume!: () => void | |
| const pending = new Promise<void>((resolve) => { | |
| resume = resolve | |
| }) | |
| this.installing.set(packageName, pending) | |
| return () => { | |
| if (this.installing.get(packageName) !== pending) return | |
| this.installing.delete(packageName) | |
| resume() | |
| } | |
| } | |
| /** | |
| * The name and age rating of the installed bundle a launch of `packageName` runs (the version `getActiveVersion` | |
| * chooses, a development snapshot included), read without waiting. The apps store checks it before it opens the | |
| * screen or stops other miniapps, so a refusal changes nothing. A live development server's rating is read when | |
| * its context spawns, where every launch is checked again. | |
| */ | |
| installedAgeRating(packageName: string): AgeRatedMiniapp { | |
| const version = appRegistry.peekActiveVersion(packageName) | |
| const manifest = version | |
| ? (appRegistry.getMiniappManifest(packageName, version) as {name?: unknown; ageRating?: unknown} | null) | |
| : null | |
| const name = typeof manifest?.name === "string" && manifest.name ? manifest.name : packageName | |
| return {packageName, name, ageRating: manifest?.ageRating ?? null} | |
| } | |
| /** Wire the router in. Called once from MiniappEngine construction. */ | |
| configure(deps: LauncherDeps): void { | |
| this.deps = deps | |
| } | |
| private requireRouter(): MentraJSRouter { | |
| if (!this.deps) { | |
| throw new Error("MiniappLauncher not configured β ensureMiniappEngine() has not run") | |
| } | |
| return this.deps.router | |
| } | |
| /** True iff the package's background JS context is currently spawned. */ | |
| isRunning(packageName: string): boolean { | |
| return this.deps?.router.registeredPackages().includes(packageName) ?? false | |
| } | |
| /** True iff the live context is projected as normal user activity. */ | |
| isProjectedRunning(packageName: string): boolean { | |
| return this.deps?.router.isProjectedRunning(packageName) ?? false | |
| } | |
| /** | |
| * Resolve the background JS source + UI entry + declared permissions for a | |
| * package. Handles both dev (HTTP off the running dev server) and released | |
| * (the installed snapshot on disk, whose screen loads from the package's own | |
| * origin). Reads disk/network/storage; does | |
| * NOT spawn. Returns null when the bundle can't be resolved (dev server | |
| * unreachable with no on-disk snapshot, missing entry, no installed version). | |
| */ | |
| async resolveBundle( | |
| packageName: string, | |
| hints?: LaunchHints, | |
| runtimeOptions?: RuntimeLaunchOptions, | |
| ): Promise<ResolvedBundle | null> { | |
| if (!isMiniappAvailable(packageName, availabilityMode(runtimeOptions))) return null | |
| const devAllowed = isDevMiniappAllowed(packageName) | |
| // Live dev code is unsigned, so it never runs under a package installed with | |
| // a publisher signature; that package runs its installed bundle instead. | |
| const liveDevAllowed = devAllowed && !appRegistry.getPublisherKeyFingerprint(packageName) | |
| const devUrl = liveDevAllowed ? (hints?.devUrl ?? this.storedDevUrl(packageName)) : undefined | |
| const selectedSnapshot = devAllowed ? appRegistry.getSelectedDevSnapshot(packageName) : null | |
| if (selectedSnapshot) return this.resolveInstalledBundle(packageName, selectedSnapshot) | |
| // --- Dev: live HTTP, then the last on-disk snapshot if the laptop is gone. --- | |
| // A stored URL from a scan that this workspace will not run must fall | |
| // through to the released bundle, or the home tile disappears. | |
| if (devUrl && devAllowed) { | |
| const source = await resolveDevBundleSource(packageName, devUrl) | |
| if (source.kind === "live") { | |
| const live = await this.resolveLiveHttp(packageName, source.resolvedUrl, source.manifest, hints) | |
| if (live) return live | |
| // Live probe succeeded but the entry fetch failed β still try disk. | |
| } | |
| const snapshotVersion = | |
| source.kind === "snapshot" ? source.version : appRegistry.getLatestDevSnapshotVersion(packageName) | |
| if (snapshotVersion) { | |
| const snapshot = await this.resolveInstalledBundle(packageName, snapshotVersion) | |
| if (snapshot) return snapshot | |
| } | |
| return null | |
| } | |
| // --- Released: resolve from the installed snapshot on disk. --- | |
| // A view can retain its old version prop across an install or rollback. | |
| // Resolve the committed pointer here, including after an installation wait. | |
| const version = await appRegistry.getActiveVersion(packageName) | |
| if (!version) return null | |
| return this.resolveInstalledBundle(packageName, version) | |
| } | |
| private async resolveLiveHttp( | |
| packageName: string, | |
| resolvedUrl: string, | |
| manifest: {entry?: unknown; permissions?: unknown; [key: string]: unknown}, | |
| hints?: LaunchHints, | |
| ): Promise<ResolvedBundle | null> { | |
| const entry = manifest.entry as {background?: string; ui?: string} | undefined | |
| if (!entry?.background) return null | |
| // Use the host that actually answered β may differ from the stored IP | |
| // after a laptop Wi-Fi change (mDNS / Metro failover inside resolveDevBundleSource). | |
| const base = resolvedUrl.replace(/\/$/, "") | |
| // entry.* are bundle-root paths (dist/ stripped); the dev server serves | |
| // files relative to cwd, so prepend dist/. | |
| const bgUrl = `${base}/dist/${entry.background.replace(/^\.?\/+/, "")}` | |
| const uiUri = entry.ui ? `${base}/dist/${entry.ui.replace(/^\.?\/+/, "")}` : null | |
| const perms = manifest.permissions as Array<{type?: string} | string> | undefined | |
| const declaredPermissions = (perms ?? []) | |
| .map((p) => (typeof p === "string" ? p : p?.type)) | |
| .filter((t): t is string => typeof t === "string") | |
| const installedManifest: InstalledMiniappManifest = { | |
| packageName: typeof manifest.packageName === "string" ? manifest.packageName : packageName, | |
| name: typeof manifest.name === "string" ? manifest.name : undefined, | |
| version: typeof manifest.version === "string" ? manifest.version : undefined, | |
| sdkVersion: typeof manifest.sdkVersion === "string" ? manifest.sdkVersion : undefined, | |
| minHostVersion: typeof manifest.minHostVersion === "string" ? manifest.minHostVersion : undefined, | |
| type: typeof manifest.type === "string" ? manifest.type : undefined, | |
| entry: manifest.entry as InstalledMiniappManifest["entry"], | |
| permissions: manifest.permissions as InstalledMiniappManifest["permissions"], | |
| hardwareRequirements: manifest.hardwareRequirements as InstalledMiniappManifest["hardwareRequirements"], | |
| actions: manifest.actions as InstalledMiniappManifest["actions"], | |
| } | |
| let bgSource: string | |
| try { | |
| const res = await fetch(bgUrl) | |
| if (!res.ok) return null | |
| bgSource = await res.text() | |
| } catch { | |
| return null | |
| } | |
| return { | |
| bgSource, | |
| uiUri, | |
| uiOrigin: uiUri ? serverOrigin(uiUri) : null, | |
| uiRootDir: null, | |
| uiOriginName: null, | |
| devBuild: true, | |
| declaredPermissions, | |
| installedManifest, | |
| ageRating: manifest.ageRating ?? null, | |
| // A dev server is never host-trusted, whatever package name it claims. | |
| hostTrustedSystem: false, | |
| devUrl: resolvedUrl, | |
| devPort: this.resolveDevPort(hints?.devPort, packageName), | |
| } | |
| } | |
| private async resolveInstalledBundle(packageName: string, version: string): Promise<ResolvedBundle | null> { | |
| const entryPaths = appRegistry.getMiniappEntryPaths(packageName, version) | |
| if (!entryPaths?.background) return null | |
| const manifest = appRegistry.getMiniappManifest(packageName, version) as { | |
| packageName?: string | |
| name?: string | |
| version?: string | |
| sdkVersion?: string | |
| minHostVersion?: string | |
| type?: string | |
| ageRating?: unknown | |
| entry?: {background?: string; ui?: string} | |
| permissions?: Array<{type: string; required?: boolean; description?: string}> | |
| hardwareRequirements?: Array<{type: string; level: string; description?: string}> | |
| actions?: Array<{ | |
| id?: unknown | |
| description?: unknown | |
| parameters?: unknown | |
| outputSchema?: unknown | |
| lifecycle?: unknown | |
| audience?: unknown | |
| }> | |
| } | null | |
| const declaredPermissions = (manifest?.permissions ?? []) | |
| .map((p) => p.type) | |
| .filter((t): t is string => typeof t === "string") | |
| const installedManifest: InstalledMiniappManifest | undefined = manifest | |
| ? { | |
| packageName: manifest.packageName ?? packageName, | |
| name: manifest.name, | |
| version: manifest.version ?? version, | |
| sdkVersion: manifest.sdkVersion, | |
| minHostVersion: manifest.minHostVersion, | |
| type: manifest.type, | |
| entry: manifest.entry, | |
| permissions: manifest.permissions, | |
| hardwareRequirements: manifest.hardwareRequirements, | |
| actions: manifest.actions, | |
| } | |
| : undefined | |
| let bgSource: string | |
| try { | |
| bgSource = new File(entryPaths.background).textSync() | |
| } catch { | |
| return null | |
| } | |
| // The screen loads from the package's own origin, which serves only this | |
| // version's bundle and never grants file access. A development snapshot | |
| // claims its name without proof, so it loads from a development origin of | |
| // that name instead and never sees a release's web storage. A package name | |
| // that can't have an origin gets no screen rather than a file:// page. | |
| const devBuild = version.startsWith("dev-") | |
| const originName = devBuild ? developmentOriginName(packageName) : packageName | |
| const platform = originPlatform() | |
| const uiUri = entryPaths.uiPath ? miniappOriginUrl(originName, entryPaths.uiPath, platform) : null | |
| if (entryPaths.uiPath && !uiUri) { | |
| console.warn(`MiniappLauncher: ${packageName} can't have an origin of its own, so its screen doesn't load`) | |
| } | |
| return { | |
| bgSource, | |
| uiUri, | |
| uiOrigin: uiUri ? miniappOrigin(originName, platform) : null, | |
| uiRootDir: uiUri ? entryPaths.rootDir : null, | |
| uiOriginName: uiUri ? originName : null, | |
| devBuild, | |
| declaredPermissions, | |
| installedManifest, | |
| ageRating: manifest?.ageRating ?? null, | |
| // A development build never runs with the build's privileges, whatever name it claims. | |
| hostTrustedSystem: | |
| !devBuild && isHostTrustedSystemMiniapp(packageName, appRegistry.getReleaseIdentity(packageName, version)), | |
| // A snapshot on disk β do not wire the sidecar; the laptop is gone. | |
| devUrl: null, | |
| devPort: null, | |
| } | |
| } | |
| /** Throws {@link MiniappIncompatibleHostError} when this Mentra App can't run the resolved bundle. */ | |
| assertRunsOnPhone(packageName: string, resolved: ResolvedBundle): void { | |
| const manifest = resolved.installedManifest | |
| const {hostVersion, supportedMiniappSdkRange} = getConfigValues() | |
| if (!manifest || !hostVersion || !supportedMiniappSdkRange) return | |
| const versions = checkManifestVersions(manifest, {hostVersion, supportedSdkRange: supportedMiniappSdkRange}) | |
| if (!versions.ok) throw new MiniappIncompatibleHostError(packageName, manifest.name || packageName, versions.reason) | |
| } | |
| /** | |
| * Ensure a miniapp's background JS context is spawned. Idempotent β if the | |
| * context is already alive this is a no-op spawn-wise (it still resolves the | |
| * UI entry so a re-mounting host gets its `<WebView>` source back). | |
| * | |
| * Resolves once the context is SPAWNED. It does NOT block on the context's | |
| * CONNECT handshake β the host's WebView mount shouldn't wait on background | |
| * JS. Callers that need the context to be connected and ready to receive | |
| * messages (the action broker) follow up with | |
| * {@link LocalMiniappRuntime.waitForConnect}. | |
| */ | |
| async ensureRunning( | |
| packageName: string, | |
| hints?: LaunchHints, | |
| runtimeOptions?: RuntimeLaunchOptions, | |
| ): Promise<LaunchResult> { | |
| // An install holds launches until its files and metadata commit or roll | |
| // back; the launch then resolves whichever bundle is active. | |
| const installation = this.installing.get(packageName) | |
| if (installation) await installation | |
| if ( | |
| !isMiniappAvailable(packageName, availabilityMode(runtimeOptions)) || | |
| !appRegistry.isPackageAllowed(packageName) | |
| ) { | |
| throw new Error(`MiniappLauncher: ${packageName} is disabled by deployment policy`) | |
| } | |
| if (appRegistry.isMiniappAccessRevoked(packageName)) throw new MiniappAccessRevokedError(packageName) | |
| const router = this.requireRouter() | |
| const projectRunning = runtimeOptions?.projectRunning ?? true | |
| // Already spawned: best-effort resolve for the UI entry, never throw β | |
| // a headless caller that doesn't need UI gets {null, null} fast even if | |
| // the dev server has since dropped. A user launch promotes a context a | |
| // transient action woke. | |
| if (router.registeredPackages().includes(packageName)) { | |
| const promoted = projectRunning && this.promote(packageName) | |
| const existing = await this.resolveBundle(packageName, hints, runtimeOptions).catch(() => null) | |
| if (promoted) this.reportLaunch(packageName, "started", runtimeOptions, existing?.installedManifest) | |
| return launchResultOf(existing) | |
| } | |
| // Coalesce concurrent launches of the same package onto one promise. | |
| const pending = this.inFlight.get(packageName) | |
| if (pending) { | |
| const joinedHidden = this.hiddenInFlight.has(packageName) | |
| let result: LaunchResult | |
| try { | |
| result = await pending | |
| } catch (error) { | |
| // A visible launch reports its own failure; one joined to a hidden wake fails with it. | |
| if (projectRunning && joinedHidden) this.reportLaunch(packageName, "failed", runtimeOptions, undefined, launchFailureReason(error)) | |
| throw error | |
| } | |
| if (projectRunning && this.promote(packageName)) this.reportLaunch(packageName, "started", runtimeOptions) | |
| return result | |
| } | |
| const launch = this.spawn(packageName, hints, {...runtimeOptions, projectRunning}) | |
| this.inFlight.set(packageName, launch) | |
| if (!projectRunning) this.hiddenInFlight.add(packageName) | |
| try { | |
| return await launch | |
| } catch (error) { | |
| if (projectRunning) this.reportLaunch(packageName, "failed", runtimeOptions, undefined, launchFailureReason(error)) | |
| throw error | |
| } finally { | |
| this.inFlight.delete(packageName) | |
| this.hiddenInFlight.delete(packageName) | |
| } | |
| } | |
| /** Projects a context already spawned as user activity: true if this made it so. */ | |
| private promote(packageName: string): boolean { | |
| const router = this.requireRouter() | |
| if (router.isProjectedRunning(packageName)) return false | |
| router.projectRunning(packageName) | |
| return router.isProjectedRunning(packageName) | |
| } | |
| /** Reports a launch this call made to Fleet, unless the apps store's `start` is making it and reports it itself. */ | |
| private reportLaunch( | |
| packageName: string, | |
| outcome: "started" | "failed", | |
| runtimeOptions?: RuntimeLaunchOptions, | |
| manifest?: InstalledMiniappManifest, | |
| failureReason?: FleetLaunchFailureReason, | |
| ): void { | |
| fleetEvents.launchUnlessClaimed({ | |
| packageName, | |
| ...(manifest?.name ? {miniappName: manifest.name} : {}), | |
| ...(manifest?.version ? {versionName: manifest.version} : {}), | |
| start: runtimeOptions?.trigger ?? "automatic", | |
| outcome, | |
| ...(outcome === "failed" ? {failureReason: failureReason ?? "unknown"} : {}), | |
| }) | |
| } | |
| /** Resolve the bundle and spawn the context. Serialized via {@link inFlight}. */ | |
| private async spawn( | |
| packageName: string, | |
| hints?: LaunchHints, | |
| runtimeOptions?: RuntimeLaunchOptions, | |
| ): Promise<LaunchResult> { | |
| const router = this.requireRouter() | |
| const resolved = await this.resolveBundle(packageName, hints, runtimeOptions) | |
| if (!resolved) { | |
| throw new Error(`MiniappLauncher: cannot resolve bundle for ${packageName}`) | |
| } | |
| // Before the age gate, so a miniapp this app can't run never asks the person's age. | |
| this.assertRunsOnPhone(packageName, resolved) | |
| const version = resolved.installedManifest?.version | |
| const projectRunning = runtimeOptions?.projectRunning ?? true | |
| // The age gate, before the deployment checks below, which then see the state after any question the person | |
| // answered. Only a launch the person makes in front of the app may ask. | |
| const verdict = await checkMiniappAge( | |
| {packageName, name: resolved.installedManifest?.name || packageName, ageRating: resolved.ageRating}, | |
| {interactive: projectRunning && AppState.currentState === "active"}, | |
| ) | |
| if (verdict !== "allowed") throw new MiniappAgeRestrictedError(packageName, verdict) | |
| // A live dev server sets devUrl. A snapshot keeps the directory name `dev-*` | |
| // as the active version. Either one is the scanned build; a release fallback is neither. | |
| const activeVersion = await appRegistry.getActiveVersion(packageName) | |
| const devBuild = Boolean(resolved.devUrl) || Boolean(activeVersion?.startsWith("dev-")) | |
| if ( | |
| // Availability may change while the bundle resolves. | |
| !isMiniappAvailable(packageName, availabilityMode(runtimeOptions)) || | |
| (devBuild ? !isDevMiniappAllowed(packageName) : !appRegistry.isReleaseAllowed(packageName, version)) | |
| ) { | |
| throw new Error(`MiniappLauncher: ${packageName} bundle is not authorized by deployment policy`) | |
| } | |
| // Re-check after the async resolve: a different path may have spawned it | |
| // while we were fetching/reading the bundle. | |
| if (router.registeredPackages().includes(packageName)) { | |
| if (projectRunning && this.promote(packageName)) { | |
| this.reportLaunch(packageName, "started", runtimeOptions, resolved.installedManifest) | |
| } | |
| } else { | |
| const ok = await router.spawnAndRegister(packageName, resolved.bgSource, { | |
| permissions: resolved.declaredPermissions, | |
| installedManifest: resolved.installedManifest, | |
| hostTrustedSystem: resolved.hostTrustedSystem, | |
| projectRunning, | |
| developmentBuild: resolved.devBuild, | |
| }) | |
| if (!ok) { | |
| throw new Error(`MiniappLauncher: spawn failed for ${packageName}`) | |
| } | |
| // Dev: wire the hot-reload + log-forwarding sidecar. No-op in prod | |
| // (devServerBridge silently drops when no sidecar is up). | |
| if (resolved.devUrl && resolved.devPort != null) { | |
| devServerBridge.connect(packageName, resolved.devUrl, resolved.devPort) | |
| } else if (resolved.devUrl) { | |
| // Dev miniapp with no resolvable port β it still launches, but hot | |
| // reload + log forwarding won't connect. Surface it instead of failing | |
| // silently (the old inline path hard-failed with "no dev port"). | |
| console.warn(`MiniappLauncher: ${packageName} has no dev port β hot reload + log forwarding disabled`) | |
| } | |
| if (projectRunning) this.reportLaunch(packageName, "started", runtimeOptions, resolved.installedManifest) | |
| } | |
| return launchResultOf(resolved) | |
| } | |
| /** | |
| * Re-spawn local miniapps that were running when the app was last killed. | |
| * | |
| * Every miniapp runs as local JavaScript in the Mentra App on the phone. | |
| * A host-process kill tears down its JSContext, so without this restoration | |
| * it stays stopped on the next launch even though the user left it running. | |
| * | |
| * Each local miniapp persists its running flag to disk on start/stop | |
| * (`saveLocalAppRunningState`, via the applet's `onStart`/`onStop`). We read | |
| * those flags back and re-spawn the background context headlessly (no | |
| * foreground, no navigation) β the spawn registers the package so the home | |
| * tray/switcher project it as running, exactly as a normal start would. The | |
| * WebView, if any, re-attaches lazily when the user opens the app. | |
| * | |
| * Idempotent and best-effort: skips already-spawned contexts and clears the | |
| * persisted running flag if ensureRunning fails (for example, bundle resolution, | |
| * deployment policy, or context spawning) so it does not retry every boot. | |
| * Each restore is an automatic launch to Fleet, reported by ensureRunning. | |
| * Not gated on the glasses' hardware: a previously-running background app shouldn't be | |
| * dropped just because glasses are momentarily disconnected at boot β it | |
| * resumes when they reconnect, same as mid-session. A release this Mentra App | |
| * can't run is refused like any launch (see {@link assertRunsOnPhone}). | |
| */ | |
| async autostartLocalMiniapps(): Promise<void> { | |
| const apps = await appRegistry.getInstalledMiniapps() | |
| for (const app of apps) { | |
| // Only phone-hosted miniapps have a JSContext to re-spawn. Offline | |
| // built-ins (`local:false, offline:true`) restore their native running | |
| // state elsewhere and have no bundle to launch. | |
| if (!app.local) continue | |
| if (!getLocalAppRunningState(app.packageName)) continue | |
| if (this.isRunning(app.packageName)) continue | |
| try { | |
| // Restoring what was running is the platform's doing, never the user's. | |
| await this.ensureRunning(app.packageName, undefined, {trigger: "automatic"}) | |
| } catch (e) { | |
| console.warn(`MiniappLauncher: autostart failed for ${app.packageName} β clearing stale running flag`, e) | |
| saveLocalAppRunningState(app.packageName, false) | |
| } | |
| } | |
| } | |
| /** | |
| * Ensure the context is running AND has completed its CONNECT handshake. | |
| * Used by the action broker, which must not deliver to a context that hasn't | |
| * come up yet. Throws on spawn failure or connect timeout. | |
| */ | |
| async ensureConnected( | |
| packageName: string, | |
| connectTimeoutMs = 10_000, | |
| hints?: LaunchHints, | |
| runtimeOptions?: RuntimeLaunchOptions, | |
| ): Promise<void> { | |
| await this.ensureRunning(packageName, hints, runtimeOptions) | |
| await localMiniappRuntime.waitForConnect(packageName, connectTimeoutMs) | |
| } | |
| /** Tear down a miniapp's background JS context. */ | |
| async stop(packageName: string): Promise<void> { | |
| // If a launch is in flight, let it finish first. Otherwise unregister() | |
| // no-ops on the not-yet-registered package and the pending spawn then | |
| // re-registers the context β leaving it running despite the stop. | |
| const pending = this.inFlight.get(packageName) | |
| if (pending) { | |
| try { | |
| await pending | |
| } catch { | |
| // Launch failed β nothing got registered, so nothing to tear down. | |
| } | |
| } | |
| await this.deps?.router.unregister(packageName) | |
| } | |
| // --- internals ----------------------------------------------------------- | |
| private storedDevUrl(packageName: string): string | undefined { | |
| const r = storage.load<string>(`${packageName}_dev_url`) | |
| return r.is_ok() ? r.value : undefined | |
| } | |
| /** resolveDevPort β moved verbatim from the old LocalMiniappView helper. */ | |
| private resolveDevPort(searchParam: string | undefined, packageName: string): number | null { | |
| if (searchParam) { | |
| const n = parseInt(searchParam, 10) | |
| if (Number.isFinite(n)) return n | |
| } | |
| const stored = storage.load<number>(`${packageName}_dev_port`) | |
| if (stored.is_ok()) return stored.value | |
| return null | |
| } | |
| } | |
| export const miniappLauncher = new MiniappLauncher() | |