Download mobile/modules/engine/src/services/LocalMiniappRuntime.ts from Anirudh1950/MentraOS: direct link, hf CLI and curl.
- Browser
- Download file 329 kB
-
https://huggingface.co/Anirudh1950/MentraOS/resolve/main/mobile/modules/engine/src/services/LocalMiniappRuntime.ts
- Command line
-
hf download hf://Anirudh1950/MentraOS/mobile/modules/engine/src/services/LocalMiniappRuntime.ts
-
curl -L -o LocalMiniappRuntime.ts https://huggingface.co/Anirudh1950/MentraOS/resolve/main/mobile/modules/engine/src/services/LocalMiniappRuntime.ts
329 kB
/**
* LocalMiniappRuntime
*
* Singleton service that bridges local miniapps (running in WebViews) with
* phone capabilities: display, audio, storage, sensors, LED, etc.
*
* Each miniapp communicates via the @mentra/miniapp envelope protocol.
* This runtime handles request dispatch, stream fan-out, and lifecycle
* management (connect/disconnect/ping).
*/
import {parsePhotoCompression} from "@mentra/cloud-protocol/photo-compression"
import {acquireGlassesHotspot} from "./GlassesHotspotLease"
import {AppState, Platform} from "react-native"
import * as Battery from "expo-battery"
import * as Clipboard from "expo-clipboard"
import * as Location from "expo-location"
import BluetoothSdk, {type RgbLedAction, type RgbLedColor} from "@mentra/bluetooth-sdk"
import {
MiniappErrorCode,
MiniappRequestType,
MiniappResponseType,
MiniappStreamType,
CLOUD_STATUS_STREAM,
parseEnvelope,
serializeEnvelope,
} from "@mentra/miniapp"
import type {MiniappEnvelope} from "@mentra/miniapp"
import {DeviceTypes, getModelCapabilities} from "../types"
import {storage as mmkvStorage} from "../utils/storage/storage"
import {BgTimer} from "../utils/timers"
import devServerBridge from "./DevServerBridge"
import {islandNotifications} from "./NotificationsEmitter"
import {isGlassesConnected, isGlassesReady, waitForGlassesReady} from "./GlassesReadiness"
import {toMiniappConnectionData} from "./GlassesStatusProjection"
import audioPlaybackService from "./AudioPlaybackService"
import {phoneLocationService} from "./PhoneLocationService"
import {useGlassesStore} from "../stores/glasses"
import {useSettingsStore} from "../stores/settings"
import localDisplayManager from "./LocalDisplayManager"
import type {DisplayPayload} from "./LocalDisplayManager"
import headingService from "./HeadingService"
import localSttFallbackCoordinator from "./LocalSttFallbackCoordinator"
import micStateCoordinator from "./MicStateCoordinator"
import {speechActivityService} from "./SpeechActivityService"
import {wakeWordService} from "./WakeWordService"
import micSessionManager, {MIC_SOURCE_CONFLICT, type MicSession} from "./MicSessionManager"
import {ENGINE_ONLY_USE_CASES, MIC_USE_CASES, VOICE_CALL_PACKAGES, type MicUseCase} from "./micPolicy"
import {BlobStore} from "./BlobStore"
import {MiniappSystemActions} from "./MiniappSystemActions"
import {CloudAudioSubscriptionSync} from "./CloudAudioSubscriptionSync"
import {phoneCameraFovCoordinator} from "./PhoneCameraFovCoordinator"
import {fleetEvents} from "./fleet/fleetEvents"
import {phonePhotoCoordinator} from "./PhonePhotoCoordinator"
import {phoneStreamCoordinator} from "./PhoneStreamCoordinator"
import {phoneVideoCoordinator} from "./PhoneVideoCoordinator"
import {runSentenceTtsPipeline} from "./SentenceTtsPipeline"
import {
needsCloud,
needsLocal,
onDeviceServes,
readSpeechProcessing,
targetSource,
UtteranceTracker,
type SpeechProcessing,
type TranscriptionRoutingState,
} from "./TranscriptionRouting"
import {
addStreamProcessing,
transcriptionRegistrations,
TranscriptionSubscriptions,
type TranscriptionStreamEntry,
} from "./TranscriptionSubscriptions"
import {prepareTtsSentences} from "./TtsTextSanitizer"
import {handleWifiAdbRequest} from "./WifiAdbRequest"
import {cloudClientService} from "./CloudClientService"
import {miniappLauncher} from "./MiniappLauncher"
import {
ISLAND_SETTINGS_KEYS,
type CameraFovPreset,
type CameraFovRequest,
type CameraRoiPosition,
type CloudClientStatusSnapshot,
type InteropAuditEvent,
type MiniappAuthToken,
type TtsSynthesisResult,
} from "../runtime/config"
import {
getAnalytics,
getConfigValues,
getMiniappConfiguration,
getUiSeams,
isFeatureEnabled,
isMiniappAvailable,
} from "../runtime/bootstrap"
import {invokeScanQrSeam} from "../runtime/scanQrSeam"
import {invokePhoneWifiSeam} from "../runtime/phoneWifiSeam"
import {
normalizeStreamAudioConfig,
normalizeStreamVideoConfig,
normalizeCaptureAudio,
resolveCaptureAudio,
} from "../runtime/streamConfig"
import {toLanguageHint} from "@mentra/cloud-protocol/languages"
import type {
AudioPosition,
AudioSubscription,
LanguageSource,
TranscriptionData,
TranslationData,
} from "@mentra/cloud-protocol"
import {buildMiniappManifestSnapshot, type MiniappRuntimeDiagnosticSnapshot} from "../utils/miniappDiagnostics"
import sttModelManager from "./STTModelManager"
import ttsModelManager from "./TTSModelManager"
import {NavigationHandlers} from "./NavigationHandlers"
import type {ClientApp} from "../types/applet"
import {useAppStatusStore, visibleMiniappPackage} from "../stores/apps"
import appRegistry, {getDevAppRecords} from "./AppRegistry"
import {resolveForegroundLocationPermission} from "./ForegroundLocationPermission"
import {advanceMiniappPingLiveness, shouldHoldMiniappPingLiveness} from "./MiniappLiveness"
import {listPhoneCalendarEvents, PhoneCalendarError} from "./PhoneCalendarService"
import {LocalMiniappStorage} from "./LocalMiniappStorage"
import {isLocalBuildContext} from "./miniappBuildKind"
import {configureMiniappDataPartitions, miniappDataSessionOf, resolveMiniappDataPartition} from "./miniappDataPartition"
import {sameCoreUrl} from "./fleet/coreUrl"
import {isHostTrustedSystemMiniapp, isSystemMiniappPackage} from "./SystemMiniappPolicy"
import {installMiniapp, InstallMiniappError, type InstallMiniappErrorCode} from "./installMiniapp"
import {dismissRunningUpdatePrompts} from "./runningUpdatePrompt"
import {
checkMiniappInstallCompatibility,
type MiniappCompatibilityPolicy,
type MiniappInstallCompatibility,
} from "./miniappInstallCompatibility"
import {TransientActionWakeCoordinator} from "./TransientActionWakeCoordinator"
import {projectSystemActions} from "./manifestActions"
import {
createMeeting,
meetingConfiguration,
meetingIdentity,
meetingCredential,
retireMeeting,
type MeetingIdentity,
} from "./MeetingCredentials"
import {loadOutgoingStill} from "./outgoingStill"
import {MeetingStillError, STILL_MAX_DURATION_MS, type MeetingStillFailure} from "./MeetingStillController"
import acsMeetingService, {
parseAcsCallOrigin,
parseAcsOutgoingVideo,
parseAcsVideoSource,
resolveAcsAudioSource,
type AcsCallOrigin,
type AcsOutgoingVideo,
type AcsVideoSource,
type MeetingState,
} from "./AcsMeetingService"
import {
createSoftapCallDeps,
SoftapCallError,
SoftapCallTransport,
RETURN_DEADLINE_MS,
SOFTAP_STEPS,
type SoftapProgress,
type SoftapTeardownMode,
} from "./SoftapCallTransport"
import {awaitCleanupBarrier} from "./SoftapCleanupBarrier"
import {softapTrace, softapTraceFailure} from "../utils/softapTrace"
import {PermissionFeatures, permissions} from "../facades/permissions"
import {getStreamPreviewHost} from "./streamPreviewPort"
// =============================================================================
// Types
// =============================================================================
export interface InstalledMiniappManifest {
packageName?: string
/** Human-facing app name (from miniapp.json `name`). Shown in the "Starting
* <name>…" boot message; falls back to the package name when absent. */
name?: string
version?: string
sdkVersion?: string
minHostVersion?: string
type?: string
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
}>
}
type SpeakerStateValue = "idle" | "loading" | "playing" | "stopped" | "error"
interface ConnectedMiniapp {
/** Transcription listeners, each with the source (cloud or on-device) it gets text from. */
transcriptionListeners: TranscriptionSubscriptions
subscriptions: Set<string>
sendMessage: (raw: string) => void
lastPongAt: number
unansweredPingRounds: number
installedManifest?: InstalledMiniappManifest
/** Host-derived provenance (a bundled release, or one from a Mentra host); never from miniapp.json. */
hostTrustedSystem: boolean
authRefreshTimerId: number | null
/**
* Backoff timer for re-attempting the INITIAL miniapp-token mint after it
* failed (distinct from `authRefreshTimerId`, which renews an already-issued
* token near expiry). Null when no retry is queued.
*/
authRetryTimerId: number | null
/**
* True once this app has received a miniapp auth token (in CONNECT_ACK or a
* follow-up AUTH_UPDATE). Gates the initial-mint retry loop and the
* on-reconnect re-drive so we stop hammering once auth has landed.
*/
authDelivered: boolean
/**
* Identifies the CONNECT handshake whose token this app is waiting for or holding (0 before its first
* CONNECT). Every token request records the value it started under and applies its answer only while the
* app still has it, so a slow answer for an earlier CONNECT or a replaced instance cannot mark the
* current handshake delivered, deliver a stale token or re-arm its timers.
*/
authSession: number
/**
* True while a request for the token this CONNECT is waiting for is out. The reconnect re-drive leaves such an
* app alone: a cache-first request now would deliver the cached token and the fresh one still on its way would
* then be discarded.
*/
authRequestPending: boolean
/** Last speaker state pushed to this app. Used to dedup SPEAKER_STATE pushes. */
speakerState: SpeakerStateValue
/** Live PCM output stream this app has open (speaker.createStream), if any. */
activeSpeakerStreamId?: string
/** Prewarmed speaker stream that hasn't received audio; the speaker stays idle until its first write. */
preparedSpeakerStreamId?: string
/** Last on-device model status sent to this app, to skip repeats. */
lastTranscriptionModelStatus?: string
/**
* Location-tier rate this app is currently asking for via its
* `location_stream` subscription, or null if it hasn't asked for
* one. The aggregate tier handed to the host is the strictest
* (highest-accuracy) rate across all currently connected apps —
* see {@link LOCATION_RATE_PRIORITY}.
*/
requestedLocationRate: string | null
/** One spawn of this package's background; a respawn gets a new id. Scopes preview leases. */
runtimeId: string
}
interface SpeechRun {
id: string
cancelled: boolean
playbackRequestId?: string
onCancelled?: () => void
}
type TranscriptionEventSource = "cloud" | "local"
/**
* Strictness ordering for `location_stream` rate values. Higher index =
* higher accuracy and higher power cost. The aggregate tier applied to
* the OS is the max of every connected miniapp's requested rate;
* miniapps that didn't ask for `location_stream` contribute nothing.
*
* If a miniapp passes a value we don't recognize, we treat it like the
* weakest known rate ("passive") rather than blanket-overwriting an
* active stronger request from another app.
*/
const LOCATION_RATE_PRIORITY = ["off", "passive", "low", "high", "realtime"] as const
type LocationRate = (typeof LOCATION_RATE_PRIORITY)[number]
function locationRateRank(rate: string | null | undefined): number {
if (!rate) return -1
const i = LOCATION_RATE_PRIORITY.indexOf(rate as LocationRate)
return i >= 0 ? i : LOCATION_RATE_PRIORITY.indexOf("passive")
}
/** Why this deployment refuses a transcription listener's processing, or null. */
function speechProcessingDisabled(processing: SpeechProcessing): string | null {
const cloud = isFeatureEnabled("cloudSpeech")
const onDevice = isFeatureEnabled("onDeviceSpeech")
if (processing === "localOnly" && !onDevice) return "On-device speech is disabled by this deployment"
if (processing === "preferCloud" && !cloud) return "Cloud speech is disabled by this deployment"
if (processing === "preferLocal" && !cloud && !onDevice) {
return "Cloud and on-device speech are disabled by this deployment"
}
return null
}
const LOG_TAG = "LOCAL_MINIAPP"
/**
* Cloud speech arrives as raw 24 kHz 16-bit mono PCM and streams into the
* native PCM player. One startup buffer for every miniapp's cloud speech:
* enough to ride out ordinary cellular jitter, short enough to start quickly.
* Tune it once on a weak cellular link; if first words get cut, raise it.
*/
const CLOUD_SPEECH_FORMAT = "pcm_24000" as const
const CLOUD_SPEECH_SAMPLE_RATE = 24000
const CLOUD_SPEECH_JITTER_MS = 250
/**
* Spoken TTS doesn't mute the cloud microphone uplink. The mute is global to
* the uplink, so arming it made every reply punch a hole in Captions and Live
* Translation for every app (removed in abd85f30a3). The PCM stream path
* supports the same opt-in; flip this to arm it for all cloud speech.
*/
const SUPPRESS_CLOUD_UPLINK_DURING_SPEECH = false
/**
* True when cloud speech failed before any audio played: the runtime refused
* it (an HTTP status, or a body that isn't PCM), or the audio output changed
* before the first byte. A dropped connection mid-sentence is not one of these.
*/
function cloudSpeechRefused(error: string | null): boolean {
return (
error !== null && /\bhttp_error\b|\bunsupported_format\b|\bnot open\b|\b(?:HTTP|status)\b|\b[45]\d\d\b/i.test(error)
)
}
const DIAGNOSTIC_MAX_LIST_ITEMS = 100
const DIAGNOSTIC_MAX_STRING_LENGTH = 512
const SYSTEM_MINIAPP_PACKAGE_SET = new Set([
"com.mentra.camera",
"com.mentra.gallery",
"com.mentra.settings",
"com.mentra.simulated",
"com.mentra.mirror",
"com.mentra.ai",
"cloud.augmentos.notify",
"com.mentra.feedback",
"com.mentra.miniappdev",
])
/** The trusted host's identity as an action caller; never a miniapp package. */
const HOST_ACTION_CALLER = "__mentra_host__"
function diagnosticStringList(values: Iterable<string>): string[] {
return [...values]
.map((value) => value.slice(0, DIAGNOSTIC_MAX_STRING_LENGTH))
.sort()
.slice(0, DIAGNOSTIC_MAX_LIST_ITEMS)
}
const PING_INTERVAL_MS = 5_000
const MINIAPP_AUTH_REFRESH_HEADROOM_MS = 5 * 60 * 1000
const MINIAPP_AUTH_REFRESH_MIN_DELAY_MS = 5_000
// Backoff bounds for re-minting the INITIAL miniapp token after a failed mint
// (e.g. the cloud client had not finished its first-boot Core token exchange
// when the miniapp connected). Exponential from base, capped, so a transient
// not-yet-connected client self-heals within seconds instead of needing a full
// manual Cloud V2 reconnect.
const MINIAPP_AUTH_RETRY_BASE_MS = 1_000
const MINIAPP_AUTH_RETRY_MAX_MS = 15_000
const FOREGROUND_LIVENESS_PROBE_TIMEOUT_MS = 2_500
/**
* How long a SoftAP call waits for the first frame to reach ACS before failing the join.
*
* Generous because it covers the glasses' whole publish path — WHIP POST, host-only ICE, and the
* first decode — but bounded, since a call that connects and never paints has to fail as a join
* rather than sit in "connecting" while the wearer waits.
*/
const SOFTAP_FIRST_FRAME_MS = 20_000
/**
* How long the BLE link must stay up before SoftAP recovery trusts it. Covers the gap between
* the hotspot dying and the phone noticing the link died with it.
*/
const GLASSES_LINK_SETTLE_MS = 4_000
const REQUEST_WIFI_SETUP_TYPE = "miniapp_request_wifi_setup"
// Unregister after this many missed pongs. Generous on purpose: a busy
// context (heavy interim translation traffic) or OS scheduling while idle can
// delay pongs well past one interval, and killing a healthy-but-busy script
// drops its subscriptions (releasing the mic). With the liveness-timeout
// respawn path wired (MentraJSRouter.start), a genuinely dead context still
// comes back automatically — this threshold only bounds how long that takes.
const PING_TIMEOUT_THRESHOLD = 6 // ~30s
const TRANSCRIPT_TIMING_TELEMETRY = (globalThis as {__DEV__?: boolean}).__DEV__ === true
const RGB_LED_ACTIONS = new Set<RgbLedAction>(["on", "off"])
const RGB_LED_COLORS = new Set<RgbLedColor>(["red", "green", "blue", "orange", "white"])
const CAMERA_FOV_MIN = 62
const CAMERA_FOV_MAX = 118
const CAMERA_FOV_DEFAULT = 118
const CAMERA_FOV_PRESETS: Record<CameraFovPreset, number> = {narrow: 82, standard: 102, wide: 118}
const CAMERA_ROI_POSITION_BY_NAME: Record<string, CameraRoiPosition> = {center: "center", bottom: "bottom", top: "top"}
const localMiniappStorageBackend = {
get(key: string): unknown | null {
const result = mmkvStorage.load<unknown>(key)
return result.is_ok() ? result.value : null
},
has(key: string): boolean {
return mmkvStorage.load<unknown>(key).is_ok()
},
set(key: string, value: unknown): void {
mmkvStorage.save(key, value)
},
remove(key: string): void {
mmkvStorage.remove(key)
},
keys(): string[] {
return mmkvStorage.getAllKeys()
},
}
configureMiniappDataPartitions({
getSession: () => miniappDataSessionOf(cloudClientService.getCoreSession(), cloudClientService.getDeploymentUserId()),
assignedWorkspace: (packageName, session) => {
const assignment = appRegistry.getMiniappAssignment(packageName)
return assignment &&
assignment.mentraUserId === session.mentraUserId &&
sameCoreUrl(assignment.coreUrl, session.coreUrl)
? assignment.workspaceId
: null
},
})
// =============================================================================
// Declared-permission record helper (for CONNECT_ACK / PERMISSIONS_UPDATE)
// =============================================================================
/**
* Map from manifest permission types (uppercase, snake-y) to the lowercase
* canonical permission keys the SDK exposes via session.permissions. Mirrors
* cloud SDK v3's PermissionType union.
*
* BACKGROUND_LOCATION + POST_NOTIFICATIONS aren't in v3's surface; they map
* onto the same canonical keys (location / notifications) since the SDK's
* `has()` is "do I have *any* form of this permission declared".
*/
const PERMISSION_TYPE_TO_CANONICAL: Record<string, string> = {
MICROPHONE: "microphone",
CAMERA: "camera",
LOCATION: "location",
BACKGROUND_LOCATION: "location",
READ_NOTIFICATIONS: "notifications",
POST_NOTIFICATIONS: "notifications",
CALENDAR: "calendar",
}
function normalizeRgbLedAction(value: unknown): RgbLedAction {
return typeof value === "string" && RGB_LED_ACTIONS.has(value as RgbLedAction) ? (value as RgbLedAction) : "off"
}
function normalizeRgbLedColor(value: unknown): RgbLedColor | null {
return typeof value === "string" && RGB_LED_COLORS.has(value as RgbLedColor) ? (value as RgbLedColor) : null
}
function normalizeCameraFovPayload(payload: Record<string, unknown>): CameraFovRequest {
if (typeof payload.preset === "string") {
const preset = payload.preset in CAMERA_FOV_PRESETS ? (payload.preset as CameraFovPreset) : "standard"
return {preset}
}
const rawFov = typeof payload.fov === "number" && Number.isFinite(payload.fov) ? payload.fov : CAMERA_FOV_DEFAULT
return {
fov: Math.min(CAMERA_FOV_MAX, Math.max(CAMERA_FOV_MIN, rawFov)),
roiPosition: normalizeCameraRoiPosition(payload.roiPosition ?? payload.roi_position),
}
}
function normalizeCameraRoiPosition(value: unknown): CameraRoiPosition {
if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2) {
return value === 1 ? "bottom" : value === 2 ? "top" : "center"
}
if (typeof value === "string") {
return CAMERA_ROI_POSITION_BY_NAME[value] ?? "center"
}
return "center"
}
const ALL_CANONICAL_PERMISSIONS = ["location", "microphone", "camera", "notifications", "calendar"] as const
/**
* Build the {location, microphone, camera, notifications, calendar} record the
* SDK's session.permissions module reads from. Missing types are false.
*/
function computeDeclaredPermissionRecord(manifest: InstalledMiniappManifest | undefined): Record<string, boolean> {
const record: Record<string, boolean> = {}
for (const k of ALL_CANONICAL_PERMISSIONS) record[k] = false
for (const perm of manifest?.permissions ?? []) {
const canonical = PERMISSION_TYPE_TO_CANONICAL[perm.type?.toUpperCase()]
if (canonical) record[canonical] = true
}
return record
}
// =============================================================================
// PERMISSION_NOT_DECLARED warnings — per-session dedup
// =============================================================================
//
// When a miniapp tries to subscribe / call something whose required permission
// isn't declared in miniapp.json, the runtime rejects with
// PERMISSION_NOT_DECLARED. The error reaches the SDK but most authors don't
// subscribe to session.on("error", ...), so it's silent in practice.
//
// To make the failure discoverable for developers running the MentraOS app
// from source, log a clear, copy-pasteable message in the phone console that
// names the offending permission, the offending stream/op, and the JSON
// snippet to add to miniapp.json. Once-per-session per (packageName, permission)
// to avoid spam from a tight retry loop.
//
// Production users running the App Store build of MentraOS won't see these
// (they don't watch Metro/adb logcat). For them, the WebView console bridge
// (#5 of the quick-fixes round) ships the structured error to the miniapp
// itself, and the miniapp's own console.warn flows to the dev terminal.
const warnedPermission = new Set<string>() // key: `${packageName}::${permission}`
function logPermissionNotDeclared(
packageName: string,
permission: string,
context: string,
manifestSnippet: string,
): void {
const key = `${packageName}::${permission}`
if (warnedPermission.has(key)) return
warnedPermission.add(key)
console.warn(
`${LOG_TAG}: ${packageName} attempted ${context}, but permission ${permission} is not declared in miniapp.json.\n` +
`Add this to the "permissions" array:\n ${manifestSnippet}`,
)
}
/** Reset the per-session dedup; called when a miniapp unregisters so a fresh launch warns again. */
function resetPermissionWarnings(packageName: string): void {
for (const key of warnedPermission) {
if (key.startsWith(`${packageName}::`)) warnedPermission.delete(key)
}
}
/**
* One attempt to start a SoftAP call, from the first permission check to the last release.
*
* The unit is the attempt rather than the transport because the transport only exists for the
* second half of it. Everything the wearer can cancel — the Nearby-devices prompt, the wait for
* mobile data, the ACS sign-in — happens before `transport.start()`, and each of those leaves
* something behind (a signed-in agent, a process-wide cellular pin) that only the attempt knows
* about.
*/
type SoftapAttempt = {
id: number
packageName: string
startedAt: number
/** Set by leave, end, or a superseding join. Checked after every await the join performs. */
cancelled: boolean
/** Set only after the preceding attempt has fully settled. */
releaseHotspot?: () => void
ownsResources: boolean
transport: SoftapCallTransport | null
/** The checklist as the miniapp last saw it; preflight rows live here until `start()` takes over. */
progress: SoftapProgress
scopedLostUnsub: (() => void) | null
/**
* Mid-call media rebuild. Single-flight while [recoveryActive] is true; the promise is
* cleared when that run settles so a later walk-away can start another. Joined to the
* attempt barrier so a late re-arm cannot resurrect resources after Leave/End.
*/
recovery: Promise<void> | null
recoveryActive: boolean
recoveryDeadlineAt: number | null
/**
* The join itself, settled either way. A native call still in flight owns state the teardown
* cannot see — a `createCallAgent` mid-sign-in — so the barrier covers this as well.
*/
body: Promise<void> | null
/** Single-flight teardown, so a leave and the join's own failure path cannot both unwind. */
teardown: Promise<void> | null
/** Opens only once the attempt *and* its cleanup are finished. The next join waits on it. */
settled: Promise<void>
settledDone: boolean
markSettled: () => void
}
/** How long a stalled SoftAP cleanup goes unremarked before it is logged. It is never abandoned. */
const SOFTAP_CLEANUP_STALL_LOG_MS = 10_000
/**
* The WHIP listener's tombstone (3s) plus a margin for the close itself.
*
* Sized to the grace period rather than picked round, so an expiry here means something actually
* went wrong instead of meaning we guessed short.
*/
const SOFTAP_INGEST_CLOSE_WAIT_MS = 3_500
/** How long the glasses get to acknowledge their hotspot off, over BLE. */
const SOFTAP_HOTSPOT_OFF_ACK_MS = 5_000
/** After a forced close there is nothing left to wait for, so this only catches a real failure. */
const SOFTAP_FORCED_VERIFY_MS = 500
/**
* Rejection codes meaning the glasses replaced their Wi-Fi protocol session, not that the
* command failed.
*
* The glasses emit `wifi_protocol_session_ready` on every `glasses_ready`, which fires on BLE
* reconnects and ASG restarts — routine during a SoftAP teardown. The SDK cancels every pending
* Wi-Fi request when that lands, so a hotspot command in flight is lost even though nothing is
* actually wrong. `wifi_session_disconnected` is deliberately absent: that one is raised from the
* store update where the glasses went away, so there is nothing left to re-send to.
*/
const HOTSPOT_SESSION_REFRESH_CODES = new Set(["wifi_session_restarted", "wifi_session_changed"])
/**
* Let the restarted ASG command path settle before re-sending.
*
* `handleSetHotspotState` returns false when its network manager is not up yet, which drops the
* command silently, so an immediate re-send would just race the same initialization. Mirrors the
* retry spacing `disableHotspotWithRetry` uses for the sibling ASG-replacement case.
*/
const HOTSPOT_SESSION_RETRY_DELAY_MS = 500
/** Reject with [reason] if [work] has not settled in [ms]. The work itself is not cancellable. */
function withTimeout<T>(work: Promise<T>, ms: number, reason: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(reason)), ms)
work.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error) => {
clearTimeout(timer)
reject(error)
},
)
})
}
/** How long the next call waits for the previous one's cleanup before telling the wearer about it. */
const SOFTAP_CLEANUP_NARRATE_AFTER_MS = 250
// =============================================================================
// LocalMiniappRuntime
// =============================================================================
class LocalMiniappRuntime {
private static instance: LocalMiniappRuntime | null = null
/**
* The SoftAP call being started or running, if any.
*
* An *attempt*, not a transport, because the cancellable part of a SoftAP call begins long
* before the transport exists: a Nearby-devices prompt and an ACS sign-in run first, and a
* wearer who taps Cancel during either of them has to be obeyed. The attempt is registered
* before the first `await` and is what every later stage checks itself against.
*/
private softapAttempt: SoftapAttempt | null = null
/**
* The outer generation. Every async callback that can outlive an attempt checks itself against
* it and traces `softap_stale_callback` when it loses: ACS state, SoftAP progress, glasses
* stream status, scoped-network loss, and each checkpoint through the join.
*
* There are inner generations below this one — `AcsMeetingSession.joinGeneration` and
* `LocalWhipIngestSource.generation` — and they are not redundant. They fence work inside one
* native session against itself; this one fences whole attempts against each other, and only it
* knows that the wearer pressed Cancel before any of that native work existed.
*/
private softapAttemptSeq = 0
/**
* Why the previous SoftAP call's cleanup failed, if it did.
*
* Read once by the next join, which refuses rather than building on leaked state: a hotspot that
* would not turn off is precisely what makes the next call fail somewhere far less legible.
*/
private softapCleanupError: string | null = null
/**
* SoftAP teardown disables the glasses hotspot from the transport and again
* from the host barrier. Native used to throw `request_in_flight` on the
* second call, which was recorded as a cleanup failure and refused the next
* join. One queue so those overlapping disables wait their turn.
*/
private glassesHotspotCommand: Promise<unknown> = Promise.resolve()
/** Connected miniapps keyed by packageName. */
private connectedApps: Map<string, ConnectedMiniapp> = new Map()
/**
* Packages that have completed their CONNECT handshake (sent
* `miniapp_connect`, got `CONNECT_ACK`). Distinct from `connectedApps`,
* which is populated at spawn/registration time — handshake is later.
* Drives {@link waitForConnect}.
*/
private handshookApps: Set<string> = new Set()
/** Pending {@link waitForConnect} resolvers, keyed by packageName. */
private connectWaiters: Map<string, Set<(err?: Error) => void>> = new Map()
/** Ref-counted stream subscriptions: stream → set of packageNames. */
private streamSubscribers: Map<string, Set<string>> = new Map()
/** Host observers for the Mentra Live button-capture policy. */
private buttonPressSubscriberListeners = new Set<(packageNames: string[]) => void>()
/** Guards one-time wiring of the cloud transcript/translation fan-out. */
private cloudResultsWired = false
private cloudStatusWired = false
private cloudAudioSubscriptionSync = new CloudAudioSubscriptionSync()
/**
* Per-miniapp language hints from TRANSCRIPTION_CONFIG (issue 021 WP3).
* Bare ISO 639-1 codes, already registry-validated by the SDK and
* re-normalized here (defense in depth). Merged (union) into the auto-mode
* cloud transcription subscription in buildCloudAudioSubscriptions.
*/
private transcriptionHintsByApp = new Map<string, string[]>()
/**
* Microphone sessions taken through session.mic.acquire, by session id.
*
* Bookkeeping only, so a release can be matched to its owner; MicSessionManager holds the real
* leases and resolves them into hardware state.
*/
private micSessionsByApp = new Map<number, {packageName: string; session: MicSession}>()
/** Ping interval handle. */
private pingIntervalId: number | null = null
private foregroundProbeTimers: Map<string, number> = new Map()
/**
* Notified when a miniapp is unregistered for missing liveness pings.
* MentraJSRouter wires this into its crash-respawn machinery so a
* silently-stalled background script is restarted (with crash-loop
* protection) instead of staying dead — a dead background drops its
* subscriptions, which releases the mic while the webview still looks
* alive.
*/
public onLivenessTimeout: ((packageName: string) => void) | null = null
private speechRuns = new Map<string, SpeechRun>()
private runtimeSeq = 0
private authSessionSeq = 0
// Browser fallback token auth — HMAC-signed blob with a phone-local
// secret. Both issuer and verifier are the same process, so the
// secret never leaves the device.
private localSecret = `miniapp_${Date.now()}_${Math.random().toString(36).slice(2, 14)}`
private usedTokens = new Set<string>()
private constructor() {}
private readonly transientActionWakes = new TransientActionWakeCoordinator({
isContextRunning: (packageName) => miniappLauncher.isRunning(packageName),
isProjectedRunning: (packageName) => miniappLauncher.isProjectedRunning(packageName),
ensureConnectedHidden: (packageName) =>
miniappLauncher.ensureConnected(packageName, 10_000, undefined, {projectRunning: false}),
stopContext: (packageName) => miniappLauncher.stop(packageName),
})
/** Snapshot of miniapps actively subscribed to hardware button events. */
public getButtonPressSubscribers(): string[] {
return [...(this.streamSubscribers.get(MiniappStreamType.BUTTON_PRESS) ?? [])].sort()
}
/** Observe active hardware-button subscriptions. */
public onButtonPressSubscribersChanged(listener: (packageNames: string[]) => void): () => void {
this.buttonPressSubscriberListeners.add(listener)
return () => this.buttonPressSubscriberListeners.delete(listener)
}
/** Report-safe live miniapp/subscription/resource snapshot. */
public getDiagnosticSnapshot(nowMs = Date.now()): MiniappRuntimeDiagnosticSnapshot {
const connectedApps = [...this.connectedApps.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.slice(0, DIAGNOSTIC_MAX_LIST_ITEMS)
.map(([packageName, app]) => ({
packageName: packageName.slice(0, DIAGNOSTIC_MAX_STRING_LENGTH),
handshakeComplete: this.handshookApps.has(packageName),
subscriptions: diagnosticStringList(app.subscriptions),
lastMessageAgeMs: Math.max(0, nowMs - app.lastPongAt),
requestedLocationRate: app.requestedLocationRate,
hasActiveSpeakerStream: app.activeSpeakerStreamId !== undefined,
...(app.installedManifest
? {
manifest: buildMiniappManifestSnapshot(app.installedManifest, {
packageName,
name: app.installedManifest.name,
version: app.installedManifest.version,
type: app.installedManifest.type,
}),
}
: {}),
}))
const subscriptionsByStream = Object.fromEntries(
[...this.streamSubscribers.entries()]
.filter(([, packageNames]) => packageNames.size > 0)
.sort(([a], [b]) => a.localeCompare(b))
.slice(0, DIAGNOSTIC_MAX_LIST_ITEMS)
.map(([stream, packageNames]) => [
stream.slice(0, DIAGNOSTIC_MAX_STRING_LENGTH),
diagnosticStringList(packageNames),
]),
)
return {
connectedApps,
subscriptionsByStream,
resources: {
display: localDisplayManager.getDiagnosticSnapshot(),
camera: phonePhotoCoordinator.getDiagnosticSnapshot(),
video: phoneVideoCoordinator.getDiagnosticSnapshot(),
stream: phoneStreamCoordinator.getDiagnosticSnapshot(),
cameraFov: phoneCameraFovCoordinator.getDiagnosticSnapshot(),
},
}
}
private replaceStreamSubscribers(
packageName: string,
previousStreams: Iterable<string>,
nextStreams: Iterable<string>,
) {
const previousButtonSubscribers = this.getButtonPressSubscribers().join("\u0000")
for (const stream of previousStreams) {
const subscribers = this.streamSubscribers.get(stream)
if (!subscribers) continue
subscribers.delete(packageName)
if (subscribers.size === 0) this.streamSubscribers.delete(stream)
}
for (const stream of nextStreams) {
let subscribers = this.streamSubscribers.get(stream)
if (!subscribers) {
subscribers = new Set()
this.streamSubscribers.set(stream, subscribers)
}
subscribers.add(packageName)
}
const nextButtonSubscribers = this.getButtonPressSubscribers()
if (previousButtonSubscribers !== nextButtonSubscribers.join("\u0000")) {
for (const listener of this.buttonPressSubscriberListeners) {
try {
listener(nextButtonSubscribers)
} catch (error) {
console.warn(`${LOG_TAG}: button press subscriber listener threw:`, error)
}
}
}
}
/**
* Generate an HMAC-signed local session token for browser fallback auth.
* Token format: base64(JSON({userId, packageName, exp})).base64(HMAC-SHA256(payload, secret))
* Single-use, 5-minute TTL.
*/
public generateLocalToken(userId: string, packageName: string): string {
const payload = JSON.stringify({
userId,
packageName,
exp: Date.now() + 5 * 60 * 1000, // 5 min TTL
nonce: Math.random().toString(36).slice(2, 10),
})
const payloadB64 = btoa(payload)
const sig = this.hmacSign(payload)
return `${payloadB64}.${sig}`
}
/**
* Validate and consume a local session token. Single-use.
*/
public validateLocalToken(token: string): {userId: string; packageName: string} | null {
const parts = token.split(".")
if (parts.length !== 2) return null
const [payloadB64, sig] = parts
// Check single-use
if (this.usedTokens.has(token)) return null
// Verify signature
let payload: string
try {
payload = atob(payloadB64!)
} catch {
return null
}
if (this.hmacSign(payload) !== sig) return null
// Parse and check expiry
let parsed: {userId: string; packageName: string; exp: number}
try {
parsed = JSON.parse(payload)
} catch {
return null
}
if (Date.now() > parsed.exp) return null
// Mark as used
this.usedTokens.add(token)
// Prune old used tokens periodically (keep set from growing unbounded)
if (this.usedTokens.size > 1000) {
this.usedTokens.clear()
}
return {userId: parsed.userId, packageName: parsed.packageName}
}
/**
* Simple HMAC-SHA256 using Web Crypto API (available in React Native).
* Returns base64url-encoded signature.
* Falls back to a simpler hash if crypto.subtle is not available.
*/
private hmacSign(payload: string): string {
// Synchronous HMAC using a simple hash — Web Crypto's subtle.sign is async
// which doesn't fit cleanly here. For phone-local single-process auth,
// a keyed hash is sufficient.
let hash = 0
const key = this.localSecret
const input = key + payload + key
for (let i = 0; i < input.length; i++) {
const ch = input.charCodeAt(i)
hash = ((hash << 5) - hash + ch) | 0
}
// Mix in more bytes for collision resistance
let hash2 = 0x811c9dc5 // FNV offset basis
for (let i = 0; i < input.length; i++) {
hash2 ^= input.charCodeAt(i)
hash2 = Math.imul(hash2, 0x01000193) // FNV prime
}
return btoa(String(hash >>> 0) + "." + String(hash2 >>> 0))
}
public static getInstance(): LocalMiniappRuntime {
if (!LocalMiniappRuntime.instance) {
LocalMiniappRuntime.instance = new LocalMiniappRuntime()
}
return LocalMiniappRuntime.instance
}
private initialized = false
private visiblePackage: string | null = null
private visibilityUnsubscribe: (() => void) | null = null
private appStateSubscription: ReturnType<typeof AppState.addEventListener> | null = null
/**
* Initialize the runtime. Called from MantleManager.init().
* Idempotent — safe to call multiple times.
*/
public initialize(): void {
if (this.initialized) return
this.initialized = true
console.log(`${LOG_TAG}: initialize()`)
this.visiblePackage = this.currentVisiblePackage()
this.visibilityUnsubscribe = useAppStatusStore.subscribe(() => this.updateVisibility())
this.appStateSubscription = AppState.addEventListener("change", () => this.updateVisibility())
this.ensurePingLoop()
// Native background tasks can survive a previous JS runtime. Reconcile even
// when no miniapps register and the previous aggregate was already off.
this.lastAppliedLocationRate = null
this.recomputeLocationTier()
}
private currentVisiblePackage(): string | null {
return visibleMiniappPackage()
}
private updateVisibility(): void {
const next = this.currentVisiblePackage()
if (next === this.visiblePackage) return
const previous = this.visiblePackage
this.visiblePackage = next
// UI_OPEN also fires during periodic foreground resync. Only the authoritative
// selection/host-activity edge should trigger a miniapp's foreground redraw.
if (previous && this.handshookApps.has(previous)) this.sendVisibilityChange(previous, "background")
if (next && this.handshookApps.has(next)) {
this.sendVisibilityChange(next, "foreground")
// Coming back to the foreground is an open: the miniapp gets a token minted now, so what the user
// acquired while it was away (a purchase) is in the token it uses next. A miniapp still waiting for its
// first token already has a fresh mint on the way (CONNECT's, or its retry), so it is left to that.
if (this.connectedApps.get(next)?.authDelivered) {
void this.refreshMiniappAuth(next, {fresh: true}).catch((err) => {
console.warn(`${LOG_TAG}: miniapp auth refresh failed for ${next}: ${(err as Error)?.message ?? err}`)
})
}
}
}
// ===========================================================================
// App registration
// ===========================================================================
/** The installed version of a connected miniapp, for Fleet's records; undefined when it is not known. */
public installedVersionOf(packageName: string): string | undefined {
return this.connectedApps.get(packageName)?.installedManifest?.version || undefined
}
public registerApp(
packageName: string,
sendFn: (raw: string) => void,
installedManifest?: InstalledMiniappManifest,
hostTrustedSystem = false,
userVisible = true,
): void {
console.log(`${LOG_TAG}: registerApp(${packageName})`)
this.clearForegroundProbe(packageName)
// Fresh spawn → fresh handshake. Clear any prior handshake flag so
// waitForConnect() blocks until this context's own CONNECT arrives.
this.handshookApps.delete(packageName)
// If the app is already registered (e.g. QR scanned again for same package),
// tear down its old subscriptions first so streamSubscribers doesn't keep
// dangling references. The WebView will re-subscribe after its CONNECT.
if (this.connectedApps.has(packageName)) {
const existing = this.connectedApps.get(packageName)!
this.cancelSpeech(packageName)
// A crash respawn replaces the ConnectedMiniapp without going through
// unregisterApp(). Abort the old incarnation's native PCM player before
// its only stream id is lost. Target the exact stream rather than using
// stopForApp(), whose async playback cleanup could race with audio the
// replacement app starts after it connects.
const existingSpeakerStreamId = existing.activeSpeakerStreamId
if (existingSpeakerStreamId) {
existing.activeSpeakerStreamId = undefined
void audioPlaybackService.abortStream(existingSpeakerStreamId).catch((error) => {
console.warn(`${LOG_TAG}: failed to abort speaker stream while replacing ${packageName}`, error)
})
}
if (existing.authRefreshTimerId !== null) {
BgTimer.clearTimeout(existing.authRefreshTimerId)
existing.authRefreshTimerId = null
}
if (existing.authRetryTimerId !== null) {
BgTimer.clearTimeout(existing.authRetryTimerId)
existing.authRetryTimerId = null
}
this.replaceStreamSubscribers(packageName, existing.subscriptions, [])
this.recomputeMicRequirements()
this.updateCloudSubscriptions()
// Managed streams and ACS meetings deliberately survive a respawn: the new
// incarnation re-adopts them on restore (Mentra Call does exactly this) so a
// WebView reload does not drop the wearer out of a live call. An unmanaged
// stream cannot be re-adopted — startUnmanaged rejects while any stream is
// active, even for the same owner — so release it or the respawned miniapp
// is stuck behind STREAM_ALREADY_ACTIVE until the process restarts.
// Unlike a managed stream, a preview lease is bound to the runtime that took it and is not
// re-adopted: the respawned background asks again.
getStreamPreviewHost()?.releaseRuntime(packageName, existing.runtimeId, "runtime_replaced")
const streamSnapshot = phoneStreamCoordinator.getDiagnosticSnapshot()
if (
streamSnapshot.active === true &&
streamSnapshot.kind === "unmanaged" &&
streamSnapshot.ownerPackageName === packageName
) {
void phoneStreamCoordinator.stop(packageName).catch((error) => {
console.warn(`${LOG_TAG}: failed to stop unmanaged stream while replacing ${packageName}`, error)
})
}
}
this.connectedApps.set(packageName, {
subscriptions: new Set(),
transcriptionListeners: new TranscriptionSubscriptions(),
sendMessage: sendFn,
lastPongAt: Date.now(),
unansweredPingRounds: 0,
installedManifest,
hostTrustedSystem,
authRefreshTimerId: null,
authRetryTimerId: null,
authDelivered: false,
authSession: 0,
authRequestPending: false,
speakerState: "idle",
requestedLocationRate: null,
runtimeId: `rt-${++this.runtimeSeq}`,
})
// If we just clobbered an existing entry, its requestedLocationRate is
// now gone — recompute so the aggregate doesn't include a stale rate.
// The WebView will re-SUBSCRIBE shortly and the rate will reappear.
this.recomputeLocationTier()
this.ensureCloudStatusWired()
this.ensurePingLoop()
// Show the system boot message ("Starting <name>…") on the glasses for the
// bounded boot window, mirroring the cloud DisplayManager boot screen. The
// window ends early once this app pushes its first display (see
// LocalDisplayManager.request), or after ~1.5s. Fires once per spawn —
// including a crash-respawn, since each spawn is a fresh "app is starting".
// An invisible transient action wake is not the app starting for the user.
if (userVisible) localDisplayManager.onMount(packageName, installedManifest?.name ?? packageName)
}
/** A transiently woken context became normal user-visible activity. */
public onUserActivated(packageName: string): void {
const app = this.connectedApps.get(packageName)
if (!app) return
localDisplayManager.onMount(packageName, app.installedManifest?.name ?? packageName)
}
/**
* Resolve once `packageName` has completed its CONNECT handshake. If it has
* already connected, resolves immediately. Rejects if the timeout elapses
* first, or if the app is unregistered while waiting.
*
* Used by the launcher's `ensureConnected` (and thus the action broker) so a
* just-spawned target is known to be live before anything is delivered to it.
*/
public waitForConnect(packageName: string, timeoutMs: number): Promise<void> {
if (this.handshookApps.has(packageName)) return Promise.resolve()
return new Promise<void>((resolve, reject) => {
let settled = false
const waiter = (err?: Error) => {
if (settled) return
settled = true
clearTimeout(timer)
this.connectWaiters.get(packageName)?.delete(waiter)
if (err) reject(err)
else resolve()
}
const timer = setTimeout(() => {
waiter(new Error(`waitForConnect: ${packageName} did not connect within ${timeoutMs}ms`))
}, timeoutMs)
let set = this.connectWaiters.get(packageName)
if (!set) {
set = new Set()
this.connectWaiters.set(packageName, set)
}
set.add(waiter)
})
}
/** Resolve/reject all pending {@link waitForConnect} waiters for a package. */
private flushConnectWaiters(packageName: string, err?: Error): void {
const waiters = this.connectWaiters.get(packageName)
if (!waiters) return
this.connectWaiters.delete(packageName)
for (const w of waiters) w(err)
}
/**
* Invalidate the CONNECT handshake for a package whose native context is
* being replaced WITHOUT going through register/unregister — i.e. a crash
* respawn. Without this, {@link waitForConnect} would treat the dead/
* not-yet-initialized context as connected and deliver to it. Pending waiters
* are failed so a wake mid-respawn retries rather than hanging.
*/
public resetHandshake(packageName: string): void {
this.handshookApps.delete(packageName)
this.flushConnectWaiters(packageName, new Error(`${packageName} respawning`))
}
/**
* Attach (or update) the installedManifest for an already-registered app.
* Used when the manifest is fetched asynchronously (dev miniapps) after the
* miniapp has already CONNECTed — preserves existing subscriptions.
*/
public setInstalledManifest(packageName: string, installedManifest: InstalledMiniappManifest): void {
const app = this.connectedApps.get(packageName)
if (!app) return
app.installedManifest = installedManifest
// Push declared-permission record to the SDK so session.permissions stays
// in sync. Sent regardless of CONNECT_ACK timing — covers the dev-miniapp
// case where the manifest is fetched async after the miniapp CONNECTs.
this.sendToMiniapp(packageName, {
type: MiniappResponseType.PERMISSIONS_UPDATE,
permissions: computeDeclaredPermissionRecord(installedManifest),
})
}
/**
* Graceful version of {@link unregisterApp}: notify the miniapp via
* `WILL_DISCONNECT`, wait ~50ms so its `beforeDisconnect` handlers can
* fire one last `sendOneShot` (e.g. `display.clear()`), then run the
* normal teardown. Use this for any disconnect path where the socket
* is still open. For ungraceful paths (transport already closed),
* call {@link unregisterApp} directly — the heads-up would be
* undeliverable anyway.
*/
public async gracefullyUnregisterApp(packageName: string, reason = "unregistering"): Promise<void> {
const app = this.connectedApps.get(packageName)
if (!app) return
console.log(`${LOG_TAG}: gracefullyUnregisterApp(${packageName}) — sending WILL_DISCONNECT`)
this.sendToMiniapp(packageName, {
type: MiniappResponseType.WILL_DISCONNECT,
reason,
})
// 50 ms: imperceptible to the user, plenty of time for the SDK's
// synchronous `beforeDisconnect` handlers to flush a final
// sendOneShot through the still-open transport.
await new Promise<void>((resolve) => setTimeout(resolve, 50))
this.unregisterApp(packageName)
}
public unregisterApp(packageName: string): void {
console.log(`${LOG_TAG}: unregisterApp(${packageName})`)
this.clearActionState(packageName)
const releasedMicGateOverride = micStateCoordinator.clearMiniappGateOverrides(packageName)
// Backstop for a miniapp that crashed or was killed mid-call: the microphone profile and the
// PCM claim must not outlive the app that asked for them.
this.forgetMicSessions(packageName)
micSessionManager.releaseOwner(packageName)
this.clearForegroundProbe(packageName)
this.clearMiniappAuthRefresh(packageName)
this.clearMiniappAuthDeliveryRetry(packageName)
// Drop the handshake flag and fail any in-flight waitForConnect() callers
// (e.g. a wake that's mid-handshake when the app is torn down). Done before
// the early-return so it runs even if the connectedApps entry is already gone.
this.handshookApps.delete(packageName)
this.flushConnectWaiters(packageName, new Error(`${packageName} unregistered before connect`))
// Drop this app's transcription hints; the cloud subscription rebuild
// below (via replaceStreamSubscribers) re-derives the hint union without it.
this.transcriptionHintsByApp.delete(packageName)
// Warm-up is a request-owned camera lease. Cancel it even if the app record was already
// removed so a close racing the camera-open promise cannot leave the sensor running.
// Close all camera consumers before restoring FOV. A shared publisher may
// remain active for another subscriber; a rejected FOV release then stops
// renewing the departed owner's lease and ASG restores it once idle.
const cameraCleanup = Promise.allSettled([
this.leaveMeetingForApp(packageName),
phonePhotoCoordinator.stopWarmUpForApp(packageName),
phoneStreamCoordinator.stop(packageName),
phoneVideoCoordinator.stopForApp(packageName),
]).then((results) => {
for (const result of results) {
if (result.status === "rejected") {
console.warn(`${LOG_TAG}: failed to stop miniapp resource for ${packageName} on unregister`, result.reason)
}
}
})
void phoneCameraFovCoordinator.releaseForApp(packageName, cameraCleanup).catch((error) => {
console.warn(`${LOG_TAG}: failed to release camera FOV override for ${packageName} on unregister`, error)
})
const app = this.connectedApps.get(packageName)
if (!app) {
if (releasedMicGateOverride) {
void micStateCoordinator.syncEffectiveGatePolicy(this.getConfiguredMicGates()).catch((error) => {
console.warn(`${LOG_TAG}: failed to restore mic gate policy for ${packageName}`, error)
})
}
return
}
getStreamPreviewHost()?.releaseRuntime(packageName, app.runtimeId, "runtime_stopped")
// Remove from all stream subscriber sets
this.replaceStreamSubscribers(packageName, app.subscriptions, [])
// Reset per-session warning dedup so a relaunch surfaces issues again.
resetPermissionWarnings(packageName)
// Cancel lookahead/in-flight synthesis before stopping the current file so
// an interrupted sentence cannot advance and reclaim playback.
this.cancelSpeech(packageName)
// Stop audio for this app, including a prewarmed stream that never played.
audioPlaybackService.stopForApp(packageName, {includeUnstarted: true})
// Tear down this app's blob state: abort in-flight uploads + close readers
// so a crashed/closed miniapp doesn't leak partial files or file handles.
this.blobStore.onAppGone(packageName)
// Release native navigation and its GPS request when the miniapp stops.
this.navigationHandlers.onDisconnect(packageName)
// Recompute heading subscription — if this app was the last subscriber,
// the sensor will stop.
this.recomputeHeadingSubscription()
// Same for the IMU/accelerometer stream.
this.recomputeImuSubscription()
// Drop this app's location-tier request before recomputing so the
// aggregate falls back down if it was the strictest. Done before
// `connectedApps.delete` below so it doesn't matter that the iter
// in `recomputeLocationTier` is over connectedApps — clearing the
// field is enough.
app.requestedLocationRate = null
this.recomputeLocationTier()
// Release any display real estate this app held — if it owned the
// current on-glasses frame, this clears the glasses (or restores the
// core app's saved frame).
localDisplayManager.onUnmount(packageName)
this.connectedApps.delete(packageName)
this.recomputeMicRequirements()
if (releasedMicGateOverride) {
void micStateCoordinator.syncEffectiveGatePolicy(this.getConfiguredMicGates()).catch((error) => {
console.warn(`${LOG_TAG}: failed to restore mic gate policy for ${packageName}`, error)
})
}
this.updateCloudSubscriptions()
if (this.connectedApps.size === 0) {
this.stopPingLoop()
}
}
// ===========================================================================
// Inbound message handling
// ===========================================================================
public handleRawMessage(packageName: string, raw: string): void {
const envelope = parseEnvelope(raw)
if (!envelope) {
// Not a miniapp envelope — ignore (could be legacy bridge message)
return
}
const payload = envelope.payload as Record<string, unknown>
const requestType = payload.type as string | undefined
const requestId = envelope.requestId
if (!requestType) {
console.warn(`${LOG_TAG}: Envelope from ${packageName} missing payload.type`)
return
}
// ANY inbound message proves the context is alive — a busy background
// script streaming DISPLAY/storage traffic shouldn't be killed by the
// liveness watchdog just because its PONG replies queue behind real work.
this.handlePong(packageName)
// Console-tap forwarding. The miniapp's console.log/warn/etc is wrapped
// (via injected shim from miniappGlobals.ts) to post a `dev_log`
// envelope. We fan out to two destinations:
// 1. DevServerBridge — forwards to the laptop's `mentra-miniapp dev`
// terminal. No-op when there's no sidecar (installed miniapps).
// 2. React Native console — surfaces the log in Metro / Xcode console
// / adb logcat so installed-miniapp errors are still inspectable
// when there's no laptop to forward to.
if (requestType === "dev_log") {
const level = (payload.level as string | undefined) ?? "log"
const args = Array.isArray(payload.args) ? (payload.args as unknown[]) : []
const timestamp = (payload.timestamp as number | undefined) ?? Date.now()
// Source is "ui" because the single-bundle WebView console-tap
// shim in miniappGlobals.ts is the only thing that posts
// `dev_log`; the two-layer path uses a separate envelope
// (`{type:"log", source}`) routed by MentraUIRouter.
devServerBridge.forwardLog(packageName, level, args, timestamp, "ui")
const tag = `[MINIAPP ${packageName}]`
const fn = (console as unknown as Record<string, (...a: unknown[]) => void>)[level] ?? console.log
try {
fn(tag, ...args)
} catch {
console.log(tag, ...args)
}
return
}
// Dispatch
switch (requestType) {
case MiniappRequestType.CONNECT:
void this.handleConnect(packageName, payload, requestId)
break
case MiniappRequestType.AUTH_REFRESH:
void this.handleAuthRefresh(packageName, payload, requestId)
break
case MiniappRequestType.SUBSCRIBE:
this.handleSubscribe(packageName, payload, requestId)
break
case MiniappRequestType.DISPLAY:
this.handleDisplay(packageName, payload, requestId)
break
case MiniappRequestType.RENDER:
this.handleRender(packageName, payload, requestId)
break
case MiniappRequestType.PLAY_AUDIO:
this.handlePlayAudio(packageName, payload, requestId)
break
case MiniappRequestType.STOP_AUDIO:
this.handleStopAudio(packageName, payload, requestId)
break
case MiniappRequestType.SPEAK:
this.handleSpeak(packageName, payload, requestId)
break
case MiniappRequestType.SPEAKER_STREAM_OPEN:
void this.handleSpeakerStreamOpen(packageName, payload, requestId)
break
case MiniappRequestType.SPEAKER_STREAM_WRITE:
void this.handleSpeakerStreamWrite(packageName, payload, requestId)
break
case MiniappRequestType.SPEAKER_STREAM_CLOSE:
void this.handleSpeakerStreamClose(packageName, payload, requestId)
break
case MiniappRequestType.SPEAKER_STREAM_ABORT:
void this.handleSpeakerStreamAbort(packageName, payload, requestId)
break
case MiniappRequestType.RGB_LED:
void this.handleRgbLed(packageName, payload, requestId)
break
case MiniappRequestType.LOCATION_POLL:
this.handleLocationPoll(packageName, requestId)
break
case MiniappRequestType.CALENDAR_LIST_EVENTS:
void this.handleCalendarListEvents(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_START:
this.navigationHandlers.handleStart(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_STOP:
this.navigationHandlers.handleStop(packageName, requestId)
break
case MiniappRequestType.NAVIGATION_DEVIATE:
this.navigationHandlers.handleDeviate(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_SET_WRONG_SIDEWALK:
this.navigationHandlers.handleSetWrongSidewalk(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_SET_SKIP_CROSSINGS:
this.navigationHandlers.handleSetSkipCrossings(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_GET_STATE:
this.navigationHandlers.handleGetState(packageName, requestId)
break
case MiniappRequestType.NAVIGATION_COMPUTE_ROUTE:
this.navigationHandlers.handleComputeRoute(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_REVERSE_GEOCODE:
this.navigationHandlers.handleReverseGeocode(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_PLACE_AUTOCOMPLETE:
this.navigationHandlers.handlePlaceAutocomplete(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_PLACE_DETAILS:
this.navigationHandlers.handlePlaceDetails(packageName, payload, requestId)
break
case MiniappRequestType.NAVIGATION_REQUEST_PERMISSION:
this.navigationHandlers.handleRequestPermission(packageName, requestId)
break
case MiniappRequestType.STORAGE_GET:
this.handleStorageGet(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_SET:
this.handleStorageSet(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_DELETE:
this.handleStorageDelete(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_LIST:
this.handleStorageList(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_CLEAR:
this.handleStorageClear(packageName, requestId)
break
case MiniappRequestType.STORAGE_HAS:
this.handleStorageHas(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_GET_ALL:
this.handleStorageGetAll(packageName, requestId)
break
case MiniappRequestType.STORAGE_SET_MULTIPLE:
this.handleStorageSetMultiple(packageName, payload, requestId)
break
case MiniappRequestType.STORAGE_FLUSH:
// No-op today — MMKV writes through synchronously. Reserved so
// a future debounced backend can honor "flush before I quit"
// calls without breaking the API.
this.sendResult(packageName, requestId, true)
break
case MiniappRequestType.CAMERA_FOV:
void this.handleCameraFov(packageName, payload, requestId)
break
case MiniappRequestType.SET_WIFI_ADB_STATE:
void this.handleSetWifiAdbState(packageName, payload, requestId)
break
case MiniappRequestType.IMU_SET_ENABLED:
this.handleImuSetEnabled(packageName, payload, requestId)
break
case MiniappRequestType.MIC_SET_VAD_ENABLED:
void this.handleMicSetVadEnabled(packageName, payload, requestId)
break
case MiniappRequestType.MIC_SET_LOUDNESS_GATE_ENABLED:
void this.handleMicSetLoudnessGateEnabled(packageName, payload, requestId)
break
case MiniappRequestType.MIC_ACQUIRE:
this.handleMicAcquire(packageName, payload, requestId)
break
case MiniappRequestType.MIC_RELEASE:
this.handleMicRelease(packageName, payload, requestId)
break
case MiniappRequestType.PING:
// SDK should handle this itself; reply PONG just in case
this.sendToMiniapp(packageName, {type: MiniappResponseType.PONG}, requestId)
break
case MiniappResponseType.PONG: {
// Liveness already touched above for every inbound message; the
// PONG carries no other action.
break
}
case MiniappRequestType.SHARE:
void this.systemActions.handleShare(packageName, payload, requestId)
break
case MiniappRequestType.OPEN_URL:
void this.systemActions.handleOpenUrl(packageName, payload)
break
case MiniappRequestType.COPY_CLIPBOARD:
this.handleCopyClipboard(packageName, payload, requestId)
break
case MiniappRequestType.DOWNLOAD:
void this.systemActions.handleDownload(packageName, payload, requestId)
break
case MiniappRequestType.SCAN_QR:
void this.handleScanQr(packageName, payload, requestId)
break
// Persistent binary blob storage (session.blob)
case MiniappRequestType.BLOB_CREATE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleCreate(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_WRITE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleWrite(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_COMMIT:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleCommit(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_ABORT:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleAbort(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_SET_FROM_URL:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleSetFromUrl(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_IMPORT:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleImport(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_GET:
this.enqueueBlobRequest(packageName, requestId, () => this.blobStore.handleGet(packageName, payload, requestId))
break
case MiniappRequestType.BLOB_LIST:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleList(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_USAGE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleUsage(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_DELETE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleDelete(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_CLEAR:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleClear(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_OPEN_READ:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleOpenRead(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_READ:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleRead(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_CLOSE_READ:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleCloseRead(packageName, payload, requestId),
)
break
case MiniappRequestType.BLOB_SHARE:
this.enqueueBlobRequest(packageName, requestId, () =>
this.blobStore.handleShare(packageName, payload, requestId),
)
break
// Cloud-coordinated features
case MiniappRequestType.PHOTO:
void this.handlePhoto(packageName, payload, requestId)
break
case MiniappRequestType.CAMERA_WARM_UP:
void this.handleCameraWarmUp(packageName, payload, requestId)
break
case MiniappRequestType.VIDEO_RECORDING_START:
void this.handleVideoRecordingStart(packageName, payload, requestId)
break
case MiniappRequestType.VIDEO_RECORDING_STOP:
void this.handleVideoRecordingStop(packageName, payload, requestId)
break
case MiniappRequestType.STREAM_START:
void this.handleStreamStart(packageName, payload, requestId)
break
case MiniappRequestType.STREAM_STOP:
void this.handleStreamStop(packageName, payload, requestId)
break
case MiniappRequestType.MANAGED_STREAM_START:
void this.handleManagedStreamStart(packageName, payload, requestId)
break
case MiniappRequestType.MANAGED_STREAM_STOP:
void this.handleManagedStreamStop(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_GET_CONFIGURATION:
this.sendResult(packageName, requestId, true, meetingConfiguration())
break
case MiniappRequestType.MEETING_GET_IDENTITY:
void this.handleMeetingIdentity(packageName, requestId)
break
case MiniappRequestType.MEETING_CREATE:
void this.handleMeetingCreate(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_RETIRE:
void this.handleMeetingRetire(packageName, payload, requestId)
break
case MiniappRequestType.STREAM_PREVIEW_START:
void this.handleStreamPreviewStart(packageName, payload, requestId)
break
case MiniappRequestType.STREAM_PREVIEW_STOP:
void this.handleStreamPreviewStop(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_JOIN:
void this.handleMeetingJoin(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_LEAVE:
void this.handleMeetingLeave(packageName, requestId)
break
case MiniappRequestType.MEETING_ADMIT:
void this.handleMeetingAdmit(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_END:
void this.handleMeetingEnd(packageName, requestId)
break
case MiniappRequestType.MEETING_SET_MUTED:
void this.handleMeetingSetMuted(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_SET_VIDEO_ENABLED:
void this.handleMeetingSetVideoEnabled(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_UPDATE_VIDEO_SOURCE:
void this.handleMeetingUpdateVideoSource(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_GET_STATE:
void this.handleMeetingGetState(packageName, requestId)
break
case MiniappRequestType.MEETING_PAUSE_VIDEO_PUBLISHER:
void this.handleMeetingPauseVideoPublisher(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_RESUME_VIDEO_PUBLISHER:
void this.handleMeetingResumeVideoPublisher(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_SHOW_CARD:
void this.handleMeetingShowCard(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_SHOW_IMAGE:
void this.handleMeetingShowImage(packageName, payload, requestId)
break
case MiniappRequestType.MEETING_SHOW_LIVE:
void this.handleMeetingShowLive(packageName, requestId)
break
case MiniappRequestType.MEETING_CAPTURE_STILL:
void this.handleMeetingCaptureStill(packageName, payload, requestId)
break
case MiniappRequestType.PHONE_IS_WIFI_ENABLED:
case MiniappRequestType.PHONE_REQUEST_WIFI_ENABLE:
void this.handlePhoneWifiRequest(packageName, payload, requestId)
break
case REQUEST_WIFI_SETUP_TYPE:
void this.handleRequestWifiSetup(packageName, payload, requestId)
break
// Inter-miniapp interop (SYSTEM apps only)
case MiniappRequestType.MINIAPPS_LIST:
this.handleMiniappsList(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_START:
void this.handleMiniappsStart(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_STOP:
void this.handleMiniappsStop(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_INSTALL:
void this.handleMiniappsInstall(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_INSTALL_CHECK:
this.handleMiniappsInstallCheck(packageName, payload, requestId)
break
case MiniappRequestType.MINIAPPS_UNINSTALL:
void this.handleMiniappsUninstall(packageName, payload, requestId)
break
case MiniappRequestType.ACTION_INVOKE:
void this.handleActionInvoke(packageName, payload, requestId)
break
case MiniappRequestType.ACTION_RESULT:
this.handleActionResult(packageName, payload)
break
// Deferred in v1
case MiniappRequestType.DASHBOARD_CONTENT_UPDATE:
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Dashboard API is deferred in v1",
})
break
case MiniappRequestType.TRANSCRIPTION_FINISH: {
const app = this.connectedApps.get(packageName)
if (
!app?.transcriptionListeners
.routes()
.some((route) => route.processing === "localOnly" || route.source === "local") ||
!app.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: "An active local microphone transcription subscription is required",
})
break
}
void this.finishLocalUtterance().then(
(text) => this.sendResult(packageName, requestId, true, text),
(error) =>
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : String(error),
}),
)
break
}
case MiniappRequestType.TRANSCRIPTION_CONFIG:
this.handleTranscriptionConfig(packageName, payload, requestId)
break
case MiniappRequestType.READY:
// MentraJSRouter observes READY to open the UI; nothing to do here.
break
case MiniappRequestType.TELEMETRY_CAPTURE:
// A miniapp's own event (`session.telemetry.capture`). It is this package's because it came over this
// package's bridge, whatever the payload says; the Fleet collector applies the limits. One-shot: no reply.
fleetEvents.telemetry({
packageName,
...(this.connectedApps.get(packageName)?.installedManifest?.version
? {versionName: this.connectedApps.get(packageName)!.installedManifest!.version}
: {}),
event: payload.event,
properties: payload.properties,
})
break
default:
// NACK instead of silent drop (issue 021 S3): an SDK that sends a
// request this runtime doesn't implement must get a rejected promise,
// not a permanently-pending silent gap. One-shots (no requestId) can
// only be logged.
console.warn(`${LOG_TAG}: Unknown request type from ${packageName}: ${requestType}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: `Unknown or unimplemented request type: ${requestType}`,
})
break
}
}
// ===========================================================================
// Request handlers
// ===========================================================================
private async handleConnect(
packageName: string,
_payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
console.log(`${LOG_TAG}: CONNECT from ${packageName}`)
// Register if not already
const existing = this.connectedApps.get(packageName)
if (!existing) {
console.warn(`${LOG_TAG}: CONNECT from unregistered app ${packageName}, dropping — isolate already torn down`)
return
}
// Update lastPongAt so it doesn't time out right away
existing.lastPongAt = Date.now()
existing.unansweredPingRounds = 0
// Read current glasses capabilities from the settings store
const defaultWearable = useSettingsStore.getState().getSetting(ISLAND_SETTINGS_KEYS.defaultWearable) as
| DeviceTypes
| undefined
const capabilities = getModelCapabilities(defaultWearable || DeviceTypes.NONE)
// Build the declared-permission record for the SDK's session.permissions
// module. Lower-cased to match v3's PermissionType union (microphone,
// camera, location, notifications, calendar). Missing permissions default
// to false; this is manifest-declaration tracking only — OS-grant state
// is intentionally not modeled here.
const declaredPermissions = computeDeclaredPermissionRecord(existing.installedManifest)
// Fresh handshake → clear any auth state from a prior context so a stale
// retry timer can't fire against this new connection and so the retry loop
// below re-arms from scratch.
existing.authDelivered = false
existing.authSession = ++this.authSessionSeq
this.clearMiniappAuthDeliveryRetry(packageName)
// A connect is an open, so the token is minted now rather than taken from the cache: it must carry
// whatever the user has acquired since the last one. If this mint fails, the retries in
// deliverInitialMiniappAuth fall back to the cache-first path.
const authPromise = this.requestMiniappAuth(packageName, {fresh: true})
// Send CONNECT_ACK in this turn, before any await. A 1.5s auth wait let a
// concurrent unregister (dev respawn, tray stop, glasses-not-ready teardown)
// drop the ACK; Mentra Call then dies with CONNECT_ACK timeout even though
// CONNECT landed. Auth still arrives on AUTH_UPDATE.
this.sendToMiniapp(
packageName,
{
type: MiniappResponseType.CONNECT_ACK,
userId: "",
packageName,
capabilities,
permissions: declaredPermissions,
visibility: this.currentVisiblePackage() === packageName ? "foreground" : "background",
configuration: getMiniappConfiguration(packageName),
// The SDK's HostFeatures. miniappInstall: system-list miniapps may call session.miniapps.install({url});
// the Mentra Apps before it answer NOT_PERMITTED.
// telemetry: `session.telemetry.capture` reaches the workspace's Fleet Management (Phase 12).
hostFeatures: {captureAudio: true, initReady: true, transcriptionListeners: true, miniappInstall: true, telemetry: true},
},
requestId,
)
this.deliverInitialMiniappAuth(packageName, authPromise, 0)
this.sendCloudStatusToMiniapp(packageName)
// Handshake complete — unblock any launcher.waitForConnect() callers.
this.handshookApps.add(packageName)
this.flushConnectWaiters(packageName)
}
private async requestMiniappAuth(
packageName: string,
opts?: {minTtlMs?: number; fresh?: boolean},
): Promise<MiniappAuthToken | null> {
// Core owns miniapp-backend token minting. A Runtime-only deployment has
// no such capability, so fail once instead of entering the retry loop.
if (!cloudClientService.hasCore()) return null
// A local or development build may claim any package name, so its token says it is a local build: a backend
// accepts it only where it allows local builds, and it never names a workspace. Every other context gets its
// package's ordinary token.
return cloudClientService.getMiniappAuthToken(
packageName,
isLocalBuildContext(packageName) ? {...opts, localBuild: true} : opts,
)
}
private async handleAuthRefresh(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const auth = await this.refreshMiniappAuth(packageName, this.authRefreshOptions(payload))
if (!auth) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_CONNECTED,
message: "Miniapp auth is not configured",
})
return
}
this.sendResult(packageName, requestId, true, {auth})
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: (err as Error)?.message ?? "Miniapp auth refresh failed",
})
}
}
private async refreshMiniappAuth(
packageName: string,
opts?: {minTtlMs?: number; fresh?: boolean},
): Promise<MiniappAuthToken | null> {
const session = this.connectedApps.get(packageName)?.authSession
const auth = await this.requestMiniappAuth(packageName, opts)
if (!auth) return null
// The miniapp that asked may have reconnected or been replaced while the mint was out. Its successor has
// its own token on the way, so this one is neither delivered nor handed back to a requester that could be
// that successor: the SDK would apply it over the newer token.
if (!this.currentAuthApp(packageName, session)) {
throw new Error("The miniapp reconnected or stopped while its auth token was being refreshed")
}
this.scheduleMiniappAuthRefresh(packageName, auth)
this.sendToMiniapp(packageName, {
type: MiniappResponseType.AUTH_UPDATE,
auth,
})
return auth
}
/** The app registered under `packageName`, if it is still in the auth session a token request started under. */
private currentAuthApp(packageName: string, session: number | undefined): ConnectedMiniapp | undefined {
const app = this.connectedApps.get(packageName)
return app && app.authSession === session ? app : undefined
}
private authRefreshOptions(payload: Record<string, unknown>): {minTtlMs?: number} | undefined {
const minTtlMs = Number(payload.minTtlMs)
if (!Number.isFinite(minTtlMs) || minTtlMs <= 0) return undefined
return {minTtlMs}
}
private scheduleMiniappAuthRefresh(packageName: string, auth: MiniappAuthToken): void {
const app = this.connectedApps.get(packageName)
if (!app) return
this.clearMiniappAuthRefresh(packageName)
const refreshAt = auth.expiresAt - MINIAPP_AUTH_REFRESH_HEADROOM_MS
this.armMiniappAuthRefresh(packageName, Math.max(MINIAPP_AUTH_REFRESH_MIN_DELAY_MS, refreshAt - Date.now()), 0)
}
/**
* Arm the refresh timer. A refresh that fails (Core or the network is down at that moment) arms it again with the
* same backoff as the first token's delivery, until a new token lands, the miniapp reconnects or it stops; the
* miniapp must not be left holding a token that runs out.
*/
private armMiniappAuthRefresh(packageName: string, delay: number, attempt: number): void {
const app = this.connectedApps.get(packageName)
if (!app) return
const session = app.authSession
app.authRefreshTimerId = BgTimer.setTimeout(() => {
const current = this.currentAuthApp(packageName, session)
if (!current) return
current.authRefreshTimerId = null
// Fresh: the cached token is the one being replaced and has no more than the headroom left, so asking
// for it again would hand the miniapp the same token and re-arm this timer for the minimum delay.
void this.refreshMiniappAuth(packageName, {fresh: true}).catch((err) => {
console.warn(`${LOG_TAG}: miniapp auth refresh failed for ${packageName}: ${(err as Error)?.message ?? err}`)
// Nothing else (a foreground refresh, a miniapp request) has armed the timer in the meantime.
const stillCurrent = this.currentAuthApp(packageName, session)
if (!stillCurrent || stillCurrent.authRefreshTimerId !== null) return
this.armMiniappAuthRefresh(
packageName,
Math.min(MINIAPP_AUTH_RETRY_MAX_MS, MINIAPP_AUTH_RETRY_BASE_MS * 2 ** attempt),
attempt + 1,
)
})
}, delay)
}
private clearMiniappAuthRefresh(packageName: string): void {
const app = this.connectedApps.get(packageName)
if (!app || app.authRefreshTimerId === null) return
const timerId = app.authRefreshTimerId
BgTimer.clearTimeout(timerId)
app.authRefreshTimerId = null
}
/**
* Deliver the miniapp's FIRST auth token, retrying until it lands. Called from
* {@link handleConnect} when the initial mint didn't resolve in the CONNECT_ACK
* window. `inFlight` lets attempt 0 reuse the mint the handshake already
* started (avoids a redundant duplicate request); that request is fresh (see
* {@link handleConnect}). Later attempts take the default, cache-first path: a
* still-valid cached token reaches the miniapp at once while Core is
* unreachable, and with no usable cached token the default path mints. The
* foreground edge and the scheduled refresh are fresh and pick up anything
* newer.
*
* A `null` result means auth is fundamentally unavailable (no miniappAuth hook)
* — permanent, so we do NOT retry. A REJECTION means a transient failure
* (typically the cloud client isn't connection-ready yet) — retry with backoff.
* Either way we bail if the app has since disconnected, reconnected (a later CONNECT
* delivers its own token; see {@link ConnectedMiniapp.authSession}) or already got a
* token (e.g. via {@link redriveMiniappAuthDelivery} on cloud-connect).
*/
private deliverInitialMiniappAuth(
packageName: string,
inFlight: Promise<MiniappAuthToken | null> | undefined,
attempt: number,
): void {
const app = this.connectedApps.get(packageName)
if (!app || app.authDelivered) return
const session = app.authSession
app.authRequestPending = true
const mint = inFlight ?? this.requestMiniappAuth(packageName)
void mint
.then((auth) => {
const current = this.currentAuthApp(packageName, session)
if (!current) return
current.authRequestPending = false
if (current.authDelivered) return
if (!auth) return // no auth hook — permanent, don't spin
current.authDelivered = true
this.clearMiniappAuthDeliveryRetry(packageName)
this.scheduleMiniappAuthRefresh(packageName, auth)
this.sendToMiniapp(packageName, {type: MiniappResponseType.AUTH_UPDATE, auth})
})
.catch((err) => {
console.warn(
`${LOG_TAG}: miniapp auth mint failed for ${packageName} (attempt ${attempt}): ${
(err as Error)?.message ?? err
}`,
)
// A later CONNECT (or a replacement) owns its own delivery and retries.
const current = this.currentAuthApp(packageName, session)
if (!current) return
current.authRequestPending = false
this.scheduleInitialMiniappAuthRetry(packageName, attempt)
})
}
private scheduleInitialMiniappAuthRetry(packageName: string, attempt: number): void {
const app = this.connectedApps.get(packageName)
if (!app || app.authDelivered) return
this.clearMiniappAuthDeliveryRetry(packageName)
const delay = Math.min(MINIAPP_AUTH_RETRY_MAX_MS, MINIAPP_AUTH_RETRY_BASE_MS * 2 ** attempt)
app.authRetryTimerId = BgTimer.setTimeout(() => {
const current = this.connectedApps.get(packageName)
if (!current) return
current.authRetryTimerId = null
this.deliverInitialMiniappAuth(packageName, undefined, attempt + 1)
}, delay)
}
private clearMiniappAuthDeliveryRetry(packageName: string): void {
const app = this.connectedApps.get(packageName)
if (!app || app.authRetryTimerId === null) return
BgTimer.clearTimeout(app.authRetryTimerId)
app.authRetryTimerId = null
}
/**
* When the cloud client (re)connects, immediately re-attempt the initial mint
* for any handshook app still missing its token, instead of waiting out the
* backoff. This is what turns "scan a dev app before the cloud is ready" from
* "dead until you manually reconnect Cloud V2" into "authenticates on its own
* the instant the connection comes up".
*/
private redriveMiniappAuthDelivery(): void {
for (const [packageName, app] of this.connectedApps) {
if (app.authDelivered || app.authRequestPending) continue
// Only apps that finished their CONNECT handshake are in the mint-retry
// state; skip anything still mid-handshake (handleConnect owns that).
if (!this.handshookApps.has(packageName)) continue
this.clearMiniappAuthDeliveryRetry(packageName)
this.deliverInitialMiniappAuth(packageName, undefined, 0)
}
}
/**
* TRANSCRIPTION_CONFIG (issue 021 WP3): store the miniapp's language hints
* and rebuild the cloud subscription set so the auto-mode subscription
* carries them. Replies with a REQUEST_RESULT so the SDK's configure()
* promise settles: unknown hint values are an error, not a silent drop.
*/
private handleTranscriptionConfig(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const app = this.connectedApps.get(packageName)
if (!app) return
const config = (payload.config ?? {}) as Record<string, unknown>
const rawHints = config.languageHints
if (rawHints !== undefined && !Array.isArray(rawHints)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "languageHints must be an array of language codes",
})
return
}
if (rawHints === undefined || rawHints.length === 0) {
this.transcriptionHintsByApp.delete(packageName)
} else {
// Defense in depth: the SDK already validated, but the wire is untyped.
const hints: string[] = []
const invalid: string[] = []
for (const raw of rawHints as unknown[]) {
const hint = typeof raw === "string" ? toLanguageHint(raw) : null
if (hint) hints.push(hint)
else invalid.push(String(raw))
}
if (invalid.length > 0) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: `Unknown language hint(s): ${invalid.join(", ")}`,
})
return
}
this.transcriptionHintsByApp.set(packageName, [...new Set(hints)].sort())
}
this.updateCloudSubscriptions()
this.sendResult(packageName, requestId, true, {applied: true})
}
private handleSubscribe(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const app = this.connectedApps.get(packageName)
if (!app) return
const rawStreams = (payload.subscriptions ?? payload.streams) as
(string | ({rate?: string} & TranscriptionStreamEntry))[] | undefined
// Normalize: objects like {stream: "location_stream", rate: "realtime"} → extract stream name
// "location_stream" is the rate-bearing alias for "location_update".
// The strictest rate wins when multiple `location_stream` entries appear
// in one SUBSCRIBE — the same rule we apply across apps.
let requestedLocationRate: string | null = null
// What each transcription stream's entries ask for: `{stream, processing}`,
// or `{stream, forceLocal, includeCloud}` from SDKs before `processing`.
const streamProcessing = new Map<string, Set<SpeechProcessing>>()
const streams = rawStreams?.map((s) => {
if (typeof s === "object" && s !== null) {
if (s.stream === "location_stream") {
if (s.rate && locationRateRank(s.rate) > locationRateRank(requestedLocationRate)) {
requestedLocationRate = s.rate
}
return "location_update"
}
if (s.stream.startsWith("transcription:")) addStreamProcessing(streamProcessing, s)
return s.stream
}
if (s.startsWith("transcription:")) addStreamProcessing(streamProcessing, {stream: s})
return s
}) as string[] | undefined
if (!Array.isArray(streams)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "subscribe requires a subscriptions array",
})
return
}
const transcriptionListeners = transcriptionRegistrations(payload.transcriptionListeners, streams, streamProcessing)
for (const stream of streams) {
if (stream.startsWith("translation:") && !isFeatureEnabled("cloudSpeech")) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Cloud speech is disabled by this deployment",
})
return
}
if (stream === "wake_word" && !isFeatureEnabled("onDeviceSpeech")) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "On-device speech is disabled by this deployment",
})
return
}
}
for (const {processing} of transcriptionListeners) {
const disabled = speechProcessingDisabled(processing)
if (disabled) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: disabled,
})
return
}
}
console.log(`${LOG_TAG}: SUBSCRIBE from ${packageName}: [${streams.join(", ")}]`)
// Gate each stream on the permission type its data requires. The manifest
// must declare the permission (miniapp.json -> permissions) or we reject
// the whole subscribe with PERMISSION_NOT_DECLARED.
const declaredTypes = new Set((app.installedManifest?.permissions ?? []).map((p) => p.type?.toUpperCase()))
const permissionForStream = (s: string): string | null => {
if (s === "audio_chunk" || s === "vad" || s === "wake_word") return "MICROPHONE"
if (s.startsWith("transcription") || s.startsWith("translation")) return "MICROPHONE"
if (s === "location_update") return "LOCATION"
if (s === "phone_notification") return "READ_NOTIFICATIONS"
if (s === "phone_notification_dismissed") return "READ_NOTIFICATIONS"
return null
}
for (const stream of streams) {
const required = permissionForStream(stream)
if (required && !declaredTypes.has(required)) {
logPermissionNotDeclared(packageName, required, `to subscribe to "${stream}"`, `{"type": "${required}"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `${required} permission not declared in miniapp.json (required for "${stream}"). Add {"type": "${required}"} to the "permissions" array.`,
// Extra context fields read by the SDK so authors that subscribe
// to session.on("error") can format their own messages.
permission: required,
subscription: stream,
})
return
}
}
// Add new subscriptions
const previousSubscriptions = app.subscriptions
app.subscriptions = new Set(streams)
// A miniapp that subscribes to the model status again gets it again.
if (!app.subscriptions.has(MiniappStreamType.TRANSCRIPTION_MODEL_STATUS))
app.lastTranscriptionModelStatus = undefined
this.replaceStreamSubscribers(packageName, previousSubscriptions, app.subscriptions)
app.transcriptionListeners.replace(transcriptionListeners, cloudClientService.getAudioPosition())
this.recomputeMicRequirements()
this.updateCloudSubscriptions()
this.recomputeHeadingSubscription()
this.recomputeImuSubscription()
// Persist this app's requested rate (or clear it if SUBSCRIBE didn't
// include `location_stream` this time), then ask the host for the
// strictest rate across all connected apps.
app.requestedLocationRate = requestedLocationRate
this.recomputeLocationTier()
this.sendResult(packageName, requestId, true)
// Fire initial snapshot values for stateful streams so miniapps don't have
// to wait for the first change event.
this.emitInitialSnapshots(packageName, streams, previousSubscriptions)
}
private async handleCalendarListEvents(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const declared = app?.installedManifest?.permissions?.some(
(permission) => permission.type?.toUpperCase() === "CALENDAR",
)
if (!declared) {
logPermissionNotDeclared(packageName, "CALENDAR", "to list calendar events", '{"type": "CALENDAR"}')
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: 'CALENDAR permission not declared in miniapp.json. Add {"type": "CALENDAR"} to the permissions array.',
permission: "CALENDAR",
})
return
}
try {
const result = await listPhoneCalendarEvents(payload)
this.sendResult(packageName, requestId, true, result)
} catch (error) {
const known = error instanceof PhoneCalendarError
this.sendResult(packageName, requestId, false, undefined, {
code: known ? error.code : MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Failed to read phone calendar events",
})
}
}
/**
* For state-bearing streams (battery, connection), deliver the current value
* immediately on subscribe. Other streams (button press, transcription, etc.)
* are pure event streams with no "current value" to snapshot.
*/
private emitInitialSnapshots(
packageName: string,
streams: string[],
previous: ReadonlySet<string> = new Set(),
): void {
// Read the engine glasses store directly (was a host glassesStatus hook).
const gs = useGlassesStore.getState()
const glassesState = {
connected: isGlassesConnected(gs.connection),
deviceModel: gs.deviceModel,
batteryLevel: gs.batteryLevel,
charging: gs.charging,
}
const isSimulated = (glassesState.deviceModel || "").toLowerCase().includes("simulated")
for (const stream of streams) {
if (stream === MiniappStreamType.WAKE_WORD) {
// The current state once per subscription; changes follow as events.
if (previous.has(stream)) continue
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: MiniappStreamType.WAKE_WORD,
data: wakeWordService.currentStatus(),
})
} else if (stream === MiniappStreamType.TRANSCRIPTION_MODEL_STATUS) {
// Usually already sent by the subscription update; this only fills a gap.
this.sendTranscriptionModelStatus(packageName)
} else if (stream === "glasses_battery") {
// Simulated glasses have no real battery; mirror the phone's battery
// so miniapps see a sensible value during development.
if (isSimulated) {
void this.emitPhoneBatteryAs(packageName, "glasses_battery")
} else if (typeof glassesState.batteryLevel === "number" && glassesState.batteryLevel >= 0) {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "glasses_battery",
data: {
level: glassesState.batteryLevel,
charging: !!glassesState.charging,
timestamp: Date.now(),
},
})
}
} else if (stream === "phone_battery") {
void this.emitPhoneBatteryAs(packageName, "phone_battery")
} else if (stream === "glasses_connection") {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "glasses_connection",
data: {
connected: glassesState.connected,
modelName: glassesState.deviceModel || undefined,
},
})
} else if (stream === "glasses_wifi") {
// Snapshot the current glasses Wi-Fi state on subscribe (like battery).
// Read the canonical nested `wifi: {state, ssid}` from the STORE state
// (`glassesState` is the narrowed 4-field projection and has no `wifi`;
// the pre-engine host hook spread the full store, so read gs directly —
// NOT the legacy flat wifiConnected). Effective connectivity requires the
// glasses connected AND on Wi-Fi — mirrors the host's store-derived
// forward, so an already-disconnected device reports `connected: false`
// rather than silently emitting nothing. Always emits so onWifi gets an
// initial value.
const wifi = gs.wifi.state === "connected" ? gs.wifi : null
const connected = glassesState.connected === true && wifi !== null
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "glasses_wifi",
data: {
connected,
linkConnected: glassesState.connected === true,
ssid: connected ? wifi?.ssid : undefined,
localIp: connected ? wifi?.localIp : undefined,
timestamp: Date.now(),
},
})
} else if (stream === "head_position") {
// The glasses store has no headUp field (same on the pre-engine host
// hook), so this stays a no-emit until head state lands in the store.
const headUp = (gs as {headUp?: boolean}).headUp
if (typeof headUp === "boolean") {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "head_position",
data: {
position: headUp ? "up" : "down",
timestamp: Date.now(),
},
})
}
}
}
}
/**
* Read the phone's battery state right now and emit it as the given stream.
* Used for both phone_battery snapshot on subscribe, and as a stand-in for
* glasses_battery when connected to Simulated Glasses.
*/
private async emitPhoneBatteryAs(
packageName: string,
streamType: "phone_battery" | "glasses_battery",
): Promise<void> {
try {
const level = await Battery.getBatteryLevelAsync()
const state = await Battery.getBatteryStateAsync()
const charging = state === Battery.BatteryState.CHARGING || state === Battery.BatteryState.FULL
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType,
data: {
level: Math.round(level * 100),
charging,
timestamp: Date.now(),
},
})
} catch (err) {
console.log(`${LOG_TAG}: phone battery snapshot failed`, err)
}
}
private handleDisplay(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
try {
// Zombie-frame gate: a dying miniapp's last in-flight frame can arrive
// AFTER onUnmount cleared its display — repainting a dead app's UI (and
// poisoning the next boot's pre-boot restore snapshot). Killed mid-route
// nav reproduced this reliably; its 3s re-push raced the teardown.
if (!this.connectedApps.has(packageName)) {
console.log(`${LOG_TAG}: dropping display from unmounted app ${packageName}`)
return
}
if (!payload.layout || typeof payload.layout !== "object") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "display request missing layout object",
})
return
}
// Hand off to LocalDisplayManager — it owns boot/throttle/arbitration/
// expiry + the native BluetoothSdk.displayEvent call + useDisplayStore.
localDisplayManager.request(packageName, {
view: (payload.view as DisplayPayload["view"]) ?? "main",
layout: payload.layout as DisplayPayload["layout"],
durationMs: payload.durationMs as number | undefined,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: display error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Display error",
})
}
}
/**
* Scene render (session.display.render()). Same arbitration as DISPLAY, but
* the payload is a whole frame of positioned elements and the caller may be
* awaiting the outcome: LocalDisplayManager guarantees the resolver fires
* exactly once (displayed/blocked, with degraded/dropped reporting), and that
* becomes the REQUEST_RESULT data.
*/
private handleRender(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
try {
// Zombie-frame gate — see handleDisplay.
if (!this.connectedApps.has(packageName)) {
this.sendResult(packageName, requestId, true, {status: "blocked", reason: "app stopped"})
return
}
if (!Array.isArray(payload.elements)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "render request missing elements array",
})
return
}
if (
payload.ifDisplayToken !== undefined &&
(typeof payload.ifDisplayToken !== "string" || !payload.ifDisplayToken)
) {
this.sendResult(packageName, requestId, true, {status: "blocked", reason: "invalid display token"})
return
}
localDisplayManager.request(
packageName,
{
view: (payload.view as DisplayPayload["view"]) ?? "main",
ifDisplayToken: payload.ifDisplayToken as string | undefined,
scene: payload.elements as DisplayPayload["scene"],
includeTextLayout: payload.includeTextLayout === true,
durationMs: payload.durationMs as number | undefined,
},
(result) => this.sendResult(packageName, requestId, true, result),
)
} catch (err) {
console.error(`${LOG_TAG}: render error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Render error",
})
}
}
private handlePlayAudio(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const audioUrl = (payload.audioUrl ?? payload.url) as string | undefined
if (!audioUrl) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "play_audio requires an audioUrl",
})
return
}
// The player opens local files too: a file URL must be one of this miniapp's own blobs.
if (!this.systemActions.allowsMediaUrl(packageName, audioUrl)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "play_audio: audioUrl must be an http(s) or data: URL, or a file from this miniapp's blob storage",
})
return
}
const audioRequestId = requestId || `local_${Date.now()}`
const volume = typeof payload.volume === "number" ? payload.volume : 1.0
const stopOtherAudio = payload.stopOtherAudio !== false
this.cancelSpeech(packageName)
this.setSpeakerState(packageName, "loading")
audioPlaybackService.play(
{
requestId: audioRequestId,
audioUrl,
appId: packageName,
volume,
stopOtherAudio,
startPositionMs: typeof payload.startPositionMs === "number" ? payload.startPositionMs : 0,
},
(_respId, success, error, duration) => {
if (success) {
this.setSpeakerState(packageName, "stopped", {durationMs: duration ?? undefined})
} else {
this.setSpeakerState(packageName, "error", {
errorCode: MiniappErrorCode.INTERNAL,
errorMessage: error ?? "play failed",
durationMs: duration ?? undefined,
})
}
this.sendResult(
packageName,
requestId,
success,
{duration},
error
? {
code: MiniappErrorCode.INTERNAL,
message: error,
}
: undefined,
)
},
)
// Optimistic "started playing" transition. The audio service doesn't
// have a "playback actually started" callback today; cloud SDK v3 has
// the same constraint and uses optimistic timing. Microtask so the
// initial "loading" envelope flushes first.
queueMicrotask(() => this.setSpeakerState(packageName, "playing"))
}
private handleStopAudio(packageName: string, _payload: Record<string, unknown>, requestId?: string): void {
this.cancelSpeech(packageName)
audioPlaybackService.stopForApp(packageName)
this.setSpeakerState(packageName, "stopped")
this.sendResult(packageName, requestId, true)
}
// ── speaker.createStream (live PCM output) ────────────────────────────────
/** Valid PCM sample rates for speaker streams. Mirrors the SDK contract. */
private static readonly SPEAKER_STREAM_SAMPLE_RATES = new Set([16000, 24000, 48000])
private static readonly SPEAKER_STREAM_MAX_BASE64_CHARS = Math.ceil((256 * 1024) / 3) * 4
private speakerStreamCounter = 0
private async handleSpeakerStreamOpen(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
if (!app) return
// One stream per miniapp: opening a second closes the first.
const previous = app.activeSpeakerStreamId
if (previous) {
app.activeSpeakerStreamId = undefined
await audioPlaybackService.abortStream(previous).catch((error) => {
console.warn(`${LOG_TAG}: failed to abort previous speaker stream for ${packageName}`, error)
})
}
const sampleRate = typeof payload.sampleRate === "number" ? payload.sampleRate : 16000
if (!LocalMiniappRuntime.SPEAKER_STREAM_SAMPLE_RATES.has(sampleRate)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: `unsupported sampleRate ${sampleRate} (use 16000, 24000, or 48000)`,
})
return
}
const channels = typeof payload.channels === "number" ? payload.channels : 1
if (channels !== 1) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "speaker streams currently support mono PCM only",
})
return
}
const volume = typeof payload.volume === "number" ? payload.volume : 1
if (!Number.isFinite(volume) || volume < 0 || volume > 1) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "speaker stream volume must be between 0 and 1",
})
return
}
const jitterMs = payload.jitterMs
if (
jitterMs !== undefined &&
(typeof jitterMs !== "number" || !Number.isFinite(jitterMs) || jitterMs < 80 || jitterMs > 500)
) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "speaker stream jitterMs must be between 80 and 500",
})
return
}
const streamId = `spkstream_${Date.now()}_${++this.speakerStreamCounter}`
const prewarm = payload.prewarm === true
// A prewarmed stream is silent until its first write, so the speaker stays idle.
if (!prewarm) this.setSpeakerState(packageName, "loading")
try {
await audioPlaybackService.openStream({
streamId,
appId: packageName,
sampleRate,
channels,
volume,
...(typeof jitterMs === "number" ? {jitterMs} : {}),
prewarm,
stopOtherAudio: payload.stopOtherAudio !== false,
onEnded: (endedId, success, error, durationMs, started) => {
const current = this.connectedApps.get(packageName)
// Ignore completion from an app incarnation replaced by a crash
// respawn. Its abort may finish after the new app has registered and
// must not overwrite that app's speaker state.
if (current !== app) return
if (current.activeSpeakerStreamId === endedId) current.activeSpeakerStreamId = undefined
if (current.preparedSpeakerStreamId === endedId) current.preparedSpeakerStreamId = undefined
// A prewarmed stream that never played leaves the speaker as it was.
if (!started && success) return
if (success) {
this.setSpeakerState(packageName, "stopped", {durationMs: durationMs ?? undefined})
} else {
this.setSpeakerState(packageName, "error", {
errorCode: MiniappErrorCode.INTERNAL,
errorMessage: error ?? "speaker stream failed",
durationMs: durationMs ?? undefined,
})
}
},
})
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
this.setSpeakerState(packageName, "error", {
errorCode: MiniappErrorCode.INTERNAL,
errorMessage: message,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message,
})
return
}
// The native open can outlive a miniapp disconnect. Its ordinary teardown
// ran while no StreamState existed yet, so close this late result here
// instead of leaving an orphan AudioTrack/AVAudioEngine session.
if (this.connectedApps.get(packageName) !== app) {
await audioPlaybackService.abortStream(streamId)
return
}
app.activeSpeakerStreamId = streamId
app.preparedSpeakerStreamId = prewarm ? streamId : undefined
// Optimistic "playing", same as play(): the chunk player starts as soon
// as the first write lands. Microtask so "loading" flushes first.
if (!prewarm) queueMicrotask(() => this.setSpeakerState(packageName, "playing"))
this.sendResult(packageName, requestId, true, {streamId})
}
/** Resolve + validate a stream id from a payload against the app's active stream. */
private activeSpeakerStream(packageName: string, payload: Record<string, unknown>): string | null {
const streamId = typeof payload.streamId === "string" ? payload.streamId : undefined
const app = this.connectedApps.get(packageName)
if (!streamId || !app || app.activeSpeakerStreamId !== streamId) return null
return streamId
}
private async handleSpeakerStreamWrite(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streamId = this.activeSpeakerStream(packageName, payload)
if (!streamId) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "speaker stream is not open",
})
return
}
const base64 = typeof payload.base64 === "string" ? payload.base64 : ""
if (!base64 || base64.length % 4 !== 0) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "speaker stream write requires padded base64 PCM data",
})
return
}
if (base64.length > LocalMiniappRuntime.SPEAKER_STREAM_MAX_BASE64_CHARS) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PAYLOAD_TOO_LARGE,
message: "speaker stream chunk exceeds the 256 KB raw PCM limit",
})
return
}
try {
const result = await audioPlaybackService.writeStreamChunk(streamId, base64)
const app = this.connectedApps.get(packageName)
if (app?.preparedSpeakerStreamId === streamId) {
app.preparedSpeakerStreamId = undefined
this.setSpeakerState(packageName, "playing")
}
this.sendResult(packageName, requestId, true, result)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : String(error),
})
}
}
private async handleSpeakerStreamClose(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streamId = this.activeSpeakerStream(packageName, payload)
if (!streamId) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "speaker stream is not open",
})
return
}
try {
// Resolves once the buffered audio has drained; onEnded delivers the
// terminal SPEAKER_STATE ("stopped").
const result = await audioPlaybackService.closeStream(streamId)
this.sendResult(packageName, requestId, true, result)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : String(error),
})
}
}
private async handleSpeakerStreamAbort(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streamId = this.activeSpeakerStream(packageName, payload)
if (!streamId) {
// Aborting an already-gone stream is fine — abort() is idempotent.
this.sendResult(packageName, requestId, true)
return
}
try {
await audioPlaybackService.abortStream(streamId)
this.sendResult(packageName, requestId, true)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : String(error),
})
}
}
private async handleSpeak(packageName: string, payload: Record<string, unknown>, requestId?: string): Promise<void> {
const rawText = payload.text
const rawSentences =
typeof rawText === "string"
? [rawText.trim()].filter(Boolean)
: Array.isArray(rawText)
? rawText
.filter((sentence): sentence is string => typeof sentence === "string")
.map((sentence) => sentence.trim())
.filter(Boolean)
: []
const enableSanitization = payload.enableSanitization !== false
const sentences = prepareTtsSentences(rawSentences, enableSanitization)
if (sentences.length === 0) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "speak requires text or a non-empty sentence list with speakable content",
})
return
}
const cloudText = sentences.join(" ")
const voice = ((payload.voice_id ?? payload.voice) as string) || "default"
const audioRequestId = requestId || `tts_${Date.now()}`
const volume = typeof payload.volume === "number" ? payload.volume : 1.0
const stopOtherAudio = payload.stopOtherAudio !== false
const voiceSettings =
payload.voice_settings && typeof payload.voice_settings === "object"
? (payload.voice_settings as Record<string, unknown>)
: undefined
const speed = typeof voiceSettings?.speed === "number" ? voiceSettings.speed : undefined
const run: SpeechRun = {id: audioRequestId, cancelled: false}
this.cancelSpeech(packageName)
this.speechRuns.set(packageName, run)
this.setSpeakerState(packageName, "loading")
let terminalSent = false
const sendPlaybackResult = (
success: boolean,
error: string | null,
duration: number | null,
fallbackErrorMessage: string,
completed = success,
errorCode: MiniappErrorCode = MiniappErrorCode.TTS_UPSTREAM_ERROR,
) => {
if (terminalSent) return
terminalSent = true
// A superseded run still owns its bridge request, but it no longer owns
// the package's shared speaker state.
const ownsSpeakerState = this.speechRuns.get(packageName) === run
if (ownsSpeakerState) this.speechRuns.delete(packageName)
if (ownsSpeakerState) {
if (success) {
this.setSpeakerState(packageName, "stopped", {durationMs: duration ?? undefined})
} else {
this.setSpeakerState(packageName, "error", {
errorCode,
errorMessage: error ?? fallbackErrorMessage,
durationMs: duration ?? undefined,
})
}
}
this.sendResult(
packageName,
requestId,
success,
{completed, duration},
error
? {
code: errorCode,
message: error,
}
: undefined,
)
}
run.onCancelled = () => sendPlaybackResult(true, null, null, "tts playback stopped", false)
try {
const voiceExplicit = payload.voice_id !== undefined || payload.voice !== undefined
const offlineSupportsVoice =
!voiceExplicit || voice === "default" || ttsModelManager.getAvailableLanguages().some((l) => l.code === voice)
const modelId = typeof payload.model_id === "string" ? payload.model_id : undefined
// `processing` wins; SDKs before it send only `forceLocal`.
const processing = readSpeechProcessing(payload)
const cloudConnected = cloudClientService.isConnected()
console.log(
`${LOG_TAG}: TTS decision for ${packageName}: cloudConnected=${cloudConnected}, runtimeTts=yes, offlineVoice=${offlineSupportsVoice}, processing=${processing}`,
)
const playOfflineTts = async (reason?: string): Promise<boolean> => {
if (run.cancelled) return true
if (!isFeatureEnabled("onDeviceSpeech")) return false
if (!offlineSupportsVoice || !(await ttsModelManager.isModelAvailable())) {
return false
}
if (run.cancelled) return true
const languageCode = ttsModelManager.getAvailableLanguages().some((l) => l.code === voice) ? voice : undefined
const offlineSentences = sentences
if (offlineSentences.length > 1) {
let firstSentence: TtsSynthesisResult
try {
firstSentence = await ttsModelManager.synthesizeToFile(offlineSentences[0], {languageCode, speed})
} catch (offlineErr) {
if (run.cancelled) return true
console.warn(
`${LOG_TAG}: offline sentence TTS synthesize failed${reason ? ` after ${reason}` : ""}:`,
offlineErr,
)
return false
}
if (run.cancelled) {
await Promise.resolve(firstSentence.cleanup?.())
return true
}
void runSentenceTtsPipeline({
sentences: offlineSentences,
firstAudio: firstSentence,
run,
synthesize: (sentence) => ttsModelManager.synthesizeToFile(sentence, {languageCode, speed}),
play: (audio, index) =>
new Promise((resolve) => {
const sentenceRequestId = `${audioRequestId}_sentence_${index}`
run.playbackRequestId = sentenceRequestId
audioPlaybackService.play(
{
requestId: sentenceRequestId,
audioUrl: audio.audioUrl,
appId: packageName,
volume,
stopOtherAudio,
},
(_responseId, success, error, duration, completionReason) => {
if (run.playbackRequestId === sentenceRequestId) run.playbackRequestId = undefined
resolve({success, completed: completionReason === "completed", error, duration})
},
)
}),
onCleanupError: (cleanupError) => {
console.warn(`${LOG_TAG}: sentence TTS cleanup failed`, cleanupError)
},
}).then(
({success, completed, error, duration}) => {
sendPlaybackResult(success, error, duration, "offline sentence tts playback failed", completed)
},
(pipelineError: unknown) => {
const message = pipelineError instanceof Error ? pipelineError.message : String(pipelineError)
sendPlaybackResult(false, message, null, "offline sentence tts playback failed", false)
},
)
queueMicrotask(() => {
if (this.speechRuns.get(packageName) === run) this.setSpeakerState(packageName, "playing")
})
return true
}
let offlineGenerated: TtsSynthesisResult | undefined
try {
offlineGenerated = await ttsModelManager.synthesizeToFile(offlineSentences[0], {languageCode, speed})
} catch (offlineErr) {
if (run.cancelled) return true
console.warn(`${LOG_TAG}: offline TTS synthesize failed${reason ? ` after ${reason}` : ""}:`, offlineErr)
return false
}
const generated = offlineGenerated
if (run.cancelled) {
await Promise.resolve(generated.cleanup?.())
return true
}
run.playbackRequestId = audioRequestId
audioPlaybackService.play(
{
requestId: audioRequestId,
audioUrl: generated.audioUrl,
appId: packageName,
volume,
stopOtherAudio,
},
(_respId, success, error, duration, completionReason) => {
if (run.playbackRequestId === audioRequestId) run.playbackRequestId = undefined
void Promise.resolve(generated.cleanup?.()).catch((cleanupError) => {
console.warn(`${LOG_TAG}: offline TTS cleanup failed`, cleanupError)
})
sendPlaybackResult(
success,
error,
duration,
"offline tts playback failed",
completionReason === "completed",
)
},
)
queueMicrotask(() => {
if (this.speechRuns.get(packageName) === run) this.setSpeakerState(packageName, "playing")
})
return true
}
const playCloudTts = async (fallbackToOffline: boolean): Promise<boolean> => {
if (run.cancelled) return true
let audioUrl: string
try {
const source = await cloudClientService.tts.speak(cloudText, {
// Every cloud speech request skips a repeat readiness check for 30 s.
reusePreflight: true,
format: CLOUD_SPEECH_FORMAT,
...(voiceExplicit && voice !== "default" ? {voice_id: voice} : {}),
...(modelId ? {model_id: modelId} : {}),
...(voiceSettings ? {voice_settings: voiceSettings} : {}),
})
audioUrl = source.audioUrl
} catch (cloudErr) {
if (run.cancelled) return true
const error = cloudErr instanceof Error ? cloudErr.message : String(cloudErr)
console.warn(`${LOG_TAG}: cloud TTS source failed: ${error}`)
if (fallbackToOffline && (await playOfflineTts("cloud tts source failed"))) {
return true
}
sendPlaybackResult(false, error, null, "tts failed")
return true
}
if (run.cancelled) return true
// Stream the synthesis into the native PCM player as it arrives, the
// same way on both platforms; the audio never crosses into JavaScript.
run.playbackRequestId = audioRequestId
void audioPlaybackService.playPcmUrl(
{
requestId: audioRequestId,
appId: packageName,
url: audioUrl,
sampleRate: CLOUD_SPEECH_SAMPLE_RATE,
volume,
jitterMs: CLOUD_SPEECH_JITTER_MS,
stopOtherAudio,
suppressCloudUplink: SUPPRESS_CLOUD_UPLINK_DURING_SPEECH,
},
(_respId, success, error, duration, completionReason) => {
if (run.playbackRequestId === audioRequestId) run.playbackRequestId = undefined
// A refused request (HTTP error) played nothing, so offline speech
// can still say it. A connection lost mid-sentence already played
// part of it; report that instead of starting over in another voice.
if (!success && fallbackToOffline && !run.cancelled && cloudSpeechRefused(error)) {
void playOfflineTts("cloud tts request refused").then((started) => {
if (!started) sendPlaybackResult(false, error, duration, "tts failed")
})
return
}
sendPlaybackResult(success, error, duration, "tts failed", completionReason === "completed")
},
)
queueMicrotask(() => {
if (this.speechRuns.get(packageName) === run) this.setSpeakerState(packageName, "playing")
})
return true
}
if (processing === "localOnly") {
if (await playOfflineTts()) {
return
}
if (run.cancelled) return
const message = "tts unavailable: localOnly requested but offline TTS model is not available"
sendPlaybackResult(false, message, null, message, false, MiniappErrorCode.TTS_LOCAL_UNAVAILABLE)
return
}
if (processing === "preferLocal") {
// On-device first; the cloud when the offline model is missing or can't say it.
if (await playOfflineTts()) {
return
}
if (await playCloudTts(false)) {
return
}
} else {
if (cloudConnected && (await playCloudTts(true))) {
return
}
// Offline is the disconnected-cloud fallback. If the model is not
// available, preserve the old behavior by trying cloud as a last resort.
if (await playOfflineTts(cloudConnected ? undefined : "cloud disconnected")) {
return
}
if (await playCloudTts(false)) {
return
}
}
const message = "tts unavailable: no cloud TTS URL or offline TTS model"
sendPlaybackResult(false, message, null, message, false)
} catch (err) {
console.error(`${LOG_TAG}: speak error:`, err)
const message = err instanceof Error ? err.message : "TTS error"
sendPlaybackResult(false, message, null, "TTS error", false)
}
}
private cancelSpeech(packageName: string): void {
const run = this.speechRuns.get(packageName)
if (!run) return
run.cancelled = true
this.speechRuns.delete(packageName)
if (run.playbackRequestId) audioPlaybackService.cancelPlayback(run.playbackRequestId)
run.onCancelled?.()
}
private async handleRgbLed(packageName: string, payload: Record<string, unknown>, requestId?: string): Promise<void> {
const coerceNumber = (value: unknown, fallback: number): number => {
const coerced = Number(value)
return Number.isFinite(coerced) ? coerced : fallback
}
const ledRequestId = requestId || `led_${Date.now()}`
const action = normalizeRgbLedAction(payload.action)
const color = normalizeRgbLedColor(payload.color)
try {
const result = await BluetoothSdk.rgbLedControl(
ledRequestId,
packageName,
action,
color,
coerceNumber(payload.ontime, 1000),
coerceNumber(payload.offtime, 0),
coerceNumber(payload.count, 1),
)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "RGB LED command failed",
})
}
}
private async handleLocationPoll(packageName: string, requestId?: string): Promise<void> {
try {
// Expo's Android requestForegroundPermissionsAsync always delegates to
// Activity.requestPermissions(), even when permission is already granted.
// Calling it after the user presses Home therefore waits until the Activity
// resumes. Read the current grant first, and only enter the prompt flow
// while the Activity is actually foregrounded.
const permissionStartedAt = Date.now()
const permission = await resolveForegroundLocationPermission(Location, () => AppState.currentState)
const {status} = permission
console.log(
`${LOG_TAG}: location poll permission status=${status} appState=${AppState.currentState} elapsed=${
Date.now() - permissionStartedAt
}ms`,
)
if (status !== "granted") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: "Location permission not granted",
})
return
}
// Try the OS cache first — usually instant — and only fall back to
// a fresh fix if the cache is empty. Use Low accuracy on the fresh
// path so we get a cell/wifi-tower fix in ~1s instead of waiting
// for full GPS warm-up.
const locationStartedAt = Date.now()
const cached = await Location.getLastKnownPositionAsync({maxAge: 60_000})
console.log(`${LOG_TAG}: location poll cache hit=${cached !== null} elapsed=${Date.now() - locationStartedAt}ms`)
const location = cached ?? (await Location.getCurrentPositionAsync({accuracy: Location.Accuracy.Low}))
console.log(`${LOG_TAG}: location poll resolved elapsed=${Date.now() - locationStartedAt}ms`)
this.sendResult(packageName, requestId, true, {
lat: location.coords.latitude,
lng: location.coords.longitude,
accuracy: location.coords.accuracy ?? undefined,
timestamp: location.timestamp,
})
} catch (err) {
console.error(`${LOG_TAG}: location poll error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Location error",
})
}
}
// ---------------------------------------------------------------------------
// Navigation
// ---------------------------------------------------------------------------
/**
* All navigation handlers + their state live in NavigationHandlers. The
* dispatcher's NAVIGATION_* cases delegate here; the rest of the runtime
* cross-cuts navigation through {@link NavigationHandlers.onDisconnect}
* (mini-app disconnect) and {@link NavigationHandlers.isTripActive}
* (location-stream gating during a trip).
*/
private readonly navigationHandlers = new NavigationHandlers(
(packageName, envelope) => this.sendToMiniapp(packageName, envelope),
(packageName, requestId, ok, result, error) => this.sendResult(packageName, requestId, ok, result, error),
)
/**
* `session.blob` — persistent, per-app binary storage. Like NavigationHandlers,
* the BLOB_* dispatcher cases delegate here. It's a generic byte store; audio
* recording lives entirely in the miniapp (mic.onAudioChunk → chunked
* BLOB_WRITE), so nothing audio-specific runs in the host.
*/
private readonly blobStore = new BlobStore({
sendResult: (packageName, requestId, ok, result, error) =>
this.sendResult(packageName, requestId, ok, result, error),
getPartition: (packageName) => resolveMiniappDataPartition(packageName),
})
private readonly blobRequestQueues = new Map<string, Promise<void>>()
/** session.system share, download and openUrl; a file URL must name one of the miniapp's own blobs. */
private readonly systemActions = new MiniappSystemActions({
sendResult: (packageName, requestId, ok, result, error) =>
this.sendResult(packageName, requestId, ok, result, error),
ownFilesDirectory: (packageName) => this.blobStore.ownFilesDirectory(packageName),
isHostLink: (url) => getConfigValues().isHostLink?.(url) === true,
})
private readonly simpleStorage = new LocalMiniappStorage({
backend: localMiniappStorageBackend,
getPartition: async (packageName) => {
await cloudClientService.resolveMentraUserId()
return resolveMiniappDataPartition(packageName)
},
})
/**
* BlobStore's file helpers are synchronous once a user namespace is selected,
* but first-boot Core auth is not. Queue requests per app behind stable
* identity resolution so CREATE/WRITE/COMMIT ordering survives that wait.
*/
private enqueueBlobRequest(
packageName: string,
requestId: string | undefined,
operation: () => Promise<void> | void,
): void {
const app = this.connectedApps.get(packageName)
const previous = this.blobRequestQueues.get(packageName) ?? Promise.resolve()
const queued = previous.then(async () => {
try {
await cloudClientService.resolveMentraUserId()
} catch (err) {
console.error(`${LOG_TAG}: blob identity error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_CONNECTED,
message: "Blob storage is unavailable before sign-in completes",
})
return
}
// unregisterApp() or a crash-respawn may have replaced this app while
// identity resolution was pending. Never replay an old context's request
// against its replacement.
if (!app || this.connectedApps.get(packageName) !== app) return
// Invoke in request order, but do not keep the queue occupied for the
// lifetime of an async picker, download, or share sheet. CREATE/WRITE/
// COMMIT are synchronous and therefore still dispatch strictly in order.
try {
const pending = operation()
if (pending) {
void pending.catch((err) => this.handleBlobRequestError(packageName, requestId, err))
}
} catch (err) {
this.handleBlobRequestError(packageName, requestId, err)
}
})
this.blobRequestQueues.set(packageName, queued)
void queued.finally(() => {
if (this.blobRequestQueues.get(packageName) === queued) this.blobRequestQueues.delete(packageName)
})
}
private handleBlobRequestError(packageName: string, requestId: string | undefined, err: unknown): void {
console.error(`${LOG_TAG}: blob request error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Blob storage error",
})
}
/**
* Heading is a sensor stream — start the native compass when any mini
* app is subscribed to "heading_update", stop it when none are.
*/
private headingUnsub: (() => void) | null = null
private recomputeHeadingSubscription(): void {
const wantsHeading = this.streamSubscribers.has(MiniappStreamType.HEADING_UPDATE)
if (wantsHeading && !this.headingUnsub) {
// Heading sensor lives in engine (HeadingService) — subscribe directly.
this.headingUnsub = headingService.addListener((degrees: number) => {
this.forwardEvent(MiniappStreamType.HEADING_UPDATE, {degrees})
})
} else if (!wantsHeading && this.headingUnsub) {
this.headingUnsub()
this.headingUnsub = null
}
}
/**
* Accelerometer is a sensor stream — enable the glasses IMU when any mini
* app is subscribed to "accel_data", disable it when none are. Mirrors the
* heading pattern. Only G2 streams IMU today; on other devices the native
* call is a no-op so this is harmless.
*/
private imuEnabled = false
private recomputeImuSubscription(): void {
const wantsImu = this.streamSubscribers.has(MiniappStreamType.ACCEL_DATA)
if (wantsImu === this.imuEnabled) return
this.imuEnabled = wantsImu
void BluetoothSdk.setImuEnabled(wantsImu)
}
/**
* Last rate we asked the host for. Lets us skip the cross-process call
* when nothing actually changed (most SUBSCRIBE / unregister churn
* leaves the aggregate unchanged) and tracks state for the no-active-
* subscribers → tell host to back off case.
*/
private lastAppliedLocationRate: LocationRate | null = null
/**
* Recompute the aggregate location tier across every connected
* miniapp and push the result to the host. The aggregate is the
* STRICTEST rate any single app has requested — see
* {@link LOCATION_RATE_PRIORITY} — because the GPS sample rate is a
* shared OS-level setting that we can't bias per-app.
*
* Called after every SUBSCRIBE and every unregister so that when a
* realtime-requesting app goes away the tier falls back down. If no
* connected app is asking for a location rate, we tell the host
* "off" so it can drop GPS power.
*/
private recomputeLocationTier(): void {
let bestRank = -1
for (const app of this.connectedApps.values()) {
const r = app.requestedLocationRate
if (!r) continue
const rank = locationRateRank(r)
if (rank > bestRank) {
bestRank = rank
}
}
// When no app is asking, downgrade to "off". Without this we'd
// leak the last-known-strictest rate forever (the original bug).
const next: LocationRate = bestRank >= 0 ? LOCATION_RATE_PRIORITY[bestRank] : "off"
if (next === this.lastAppliedLocationRate) return
this.lastAppliedLocationRate = next
console.log(`[LOCATION] aggregate tier → ${next}`)
void phoneLocationService.setLocationTier(next)
}
// ---------------------------------------------------------------------------
// Storage helpers
// ---------------------------------------------------------------------------
private async handleStorageGet(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const key = payload.key as string
if (!key) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_get requires a key",
})
return
}
const value = await this.simpleStorage.get(packageName, key)
this.sendResult(packageName, requestId, true, {key, value})
} catch (err) {
console.error(`${LOG_TAG}: storage_get error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageSet(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const key = payload.key as string
if (!key) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_set requires a key",
})
return
}
await this.simpleStorage.set(packageName, key, payload.value ?? null)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: storage_set error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageDelete(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const key = payload.key as string
if (!key) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_delete requires a key",
})
return
}
await this.simpleStorage.delete(packageName, key)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: storage_delete error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageList(
packageName: string,
_payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const keys = await this.simpleStorage.keys(packageName)
this.sendResult(packageName, requestId, true, {keys})
} catch (err) {
console.error(`${LOG_TAG}: storage_list error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageClear(packageName: string, requestId?: string): Promise<void> {
try {
await this.simpleStorage.clear(packageName)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: storage_clear error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageHas(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const key = payload.key as string
if (!key) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_has requires a key",
})
return
}
const has = await this.simpleStorage.has(packageName, key)
this.sendResult(packageName, requestId, true, {has})
} catch (err) {
console.error(`${LOG_TAG}: storage_has error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageGetAll(packageName: string, requestId?: string): Promise<void> {
try {
const values = await this.simpleStorage.getAll(packageName)
this.sendResult(packageName, requestId, true, {values})
} catch (err) {
console.error(`${LOG_TAG}: storage_get_all error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
private async handleStorageSetMultiple(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const values = payload.values as Record<string, unknown> | undefined
if (!values || typeof values !== "object") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "storage_set_multiple requires a values object",
})
return
}
await this.simpleStorage.setMultiple(packageName, values)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: storage_set_multiple error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Storage error",
})
}
}
// ---------------------------------------------------------------------------
// Wi-Fi ADB
// ---------------------------------------------------------------------------
private async handleSetWifiAdbState(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const result = await handleWifiAdbRequest(packageName, payload, {
isSystemPackage: (candidate) => this.isSystemPackage(candidate),
setWifiAdbState: async (enabled) => {
console.log(`${LOG_TAG}: set_wifi_adb_state enabled=${enabled} from ${packageName}`)
try {
await BluetoothSdk.setWifiAdbState(enabled)
} catch (error) {
console.error(`${LOG_TAG}: set_wifi_adb_state error:`, error)
throw error
}
},
})
if (result.ok) {
this.sendResult(packageName, requestId, true)
return
}
this.sendResult(packageName, requestId, false, undefined, result.error)
}
// ---------------------------------------------------------------------------
// Camera FOV
// ---------------------------------------------------------------------------
private async handleCameraFov(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const hasCameraPermission = app?.installedManifest?.permissions?.some((p) => p.type === "CAMERA")
if (!hasCameraPermission) {
logPermissionNotDeclared(packageName, "CAMERA", "to set camera FOV", `{"type": "CAMERA"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `CAMERA permission not declared in miniapp.json. Add {"type": "CAMERA"} to the "permissions" array.`,
permission: "CAMERA",
operation: MiniappRequestType.CAMERA_FOV,
})
return
}
try {
const request = normalizeCameraFovPayload(payload)
const description =
"preset" in request ? `preset=${request.preset}` : `fov=${request.fov} roi=${request.roiPosition ?? "center"}`
console.log(`${LOG_TAG}: camera_fov_set ${description}`)
const result = await phoneCameraFovCoordinator.setOverride(packageName, request)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
console.error(`${LOG_TAG}: camera_fov error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Camera FOV error",
})
}
}
/**
* Explicit IMU enable/disable from a miniapp (session.imu.setEnabled).
*
* The accel stream already auto-toggles the native IMU on subscribe (see
* {@link recomputeImuSubscription}); this is a direct override. We sync
* `this.imuEnabled` to the requested state so a subsequent subscription
* recompute with the same aggregate doesn't issue a redundant native call.
* Note that a later subscribe/unsubscribe that changes the aggregate will
* still re-derive the sensor state from subscriptions.
*/
private handleImuSetEnabled(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
try {
const enabled = !!payload.enabled
console.log(`${LOG_TAG}: imu_set_enabled ${enabled} (by ${packageName})`)
this.imuEnabled = enabled
void BluetoothSdk.setImuEnabled(enabled)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: imu_set_enabled error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "IMU set-enabled error",
})
}
}
/**
* Lifecycle-scoped glasses-side VAD override from a miniapp
* (session.mic.setVoiceActivityDetectionEnabled). Requires MICROPHONE in the
* miniapp manifest. Mentra Live only today — other models no-op via DeviceStore.
*/
private async handleMicSetVadEnabled(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const hasMicPermission = app?.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
if (!hasMicPermission) {
logPermissionNotDeclared(packageName, "MICROPHONE", "to set VAD enabled", `{"type": "MICROPHONE"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `MICROPHONE permission not declared in miniapp.json. Add {"type": "MICROPHONE"} to the "permissions" array.`,
permission: "MICROPHONE",
operation: MiniappRequestType.MIC_SET_VAD_ENABLED,
})
return
}
if (typeof payload.enabled !== "boolean") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "enabled must be a boolean",
})
return
}
try {
const enabled = payload.enabled
console.log(`${LOG_TAG}: mic_set_vad_enabled ${enabled} (by ${packageName})`)
await micStateCoordinator.setMiniappGateOverride(packageName, "vad", enabled, this.getConfiguredMicGates())
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: mic_set_vad_enabled error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "VAD set-enabled error",
})
}
}
/**
* Lifecycle-scoped center-mic loudness gate ("Barrier") override from a miniapp
* (session.mic.setLoudnessGateEnabled). Requires MICROPHONE in the miniapp
* manifest. Mentra Live only today — other models no-op via DeviceStore.
*/
private async handleMicSetLoudnessGateEnabled(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const hasMicPermission = app?.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
if (!hasMicPermission) {
logPermissionNotDeclared(packageName, "MICROPHONE", "to set loudness gate enabled", `{"type": "MICROPHONE"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `MICROPHONE permission not declared in miniapp.json. Add {"type": "MICROPHONE"} to the "permissions" array.`,
permission: "MICROPHONE",
operation: MiniappRequestType.MIC_SET_LOUDNESS_GATE_ENABLED,
})
return
}
if (typeof payload.enabled !== "boolean") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "enabled must be a boolean",
})
return
}
try {
const enabled = payload.enabled
console.log(`${LOG_TAG}: mic_set_loudness_gate_enabled ${enabled} (by ${packageName})`)
await micStateCoordinator.setMiniappGateOverride(
packageName,
"loudnessGate",
enabled,
this.getConfiguredMicGates(),
)
this.sendResult(packageName, requestId, true)
} catch (err) {
console.error(`${LOG_TAG}: mic_set_loudness_gate_enabled error:`, err)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Loudness gate set-enabled error",
})
}
}
/**
* session.mic.acquire — take a semantic microphone session.
*
* The miniapp names a use case; MicSessionManager and micPolicy decide what that means for the
* hardware. This handler is only the gate: who is allowed to ask for what.
*/
private handleMicAcquire(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const app = this.connectedApps.get(packageName)
const hasMicPermission = app?.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
if (!hasMicPermission) {
logPermissionNotDeclared(packageName, "MICROPHONE", "to acquire a microphone session", `{"type": "MICROPHONE"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `MICROPHONE permission not declared in miniapp.json. Add {"type": "MICROPHONE"} to the "permissions" array.`,
permission: "MICROPHONE",
operation: MiniappRequestType.MIC_ACQUIRE,
})
return
}
const source = payload.source
const useCase = payload.useCase
if (source !== "glasses" && source !== "phone") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: `source must be "glasses" or "phone"`,
})
return
}
if (!MIC_USE_CASES.includes(useCase as MicUseCase)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: `useCase must be one of ${MIC_USE_CASES.join(", ")}`,
})
return
}
// A voice call gets a microphone profile tuned for close-talk speech, so which app may ask for
// one is a product decision, not a permission a manifest can grant itself.
if (useCase === "voice_call" && !VOICE_CALL_PACKAGES.includes(packageName)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: `${packageName} is not allowed to acquire a voice_call microphone session`,
})
return
}
// Diagnostic leases exist so the mic probe measures what users actually get. Handing one to a
// miniapp would also hand it a glasses lease it could pair with a meeting join.
if (ENGINE_ONLY_USE_CASES.includes(useCase as MicUseCase)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: `the ${useCase} microphone use case is reserved for the Mentra App`,
})
return
}
try {
const session = micSessionManager.acquire({owner: packageName, source, useCase: useCase as MicUseCase})
this.micSessionsByApp.set(session.id, {packageName, session})
console.log(`${LOG_TAG}: mic_acquire #${session.id} ${useCase}/${source} (by ${packageName})`)
this.sendResult(packageName, requestId, true, {sessionId: session.id})
} catch (err) {
const message = err instanceof Error ? err.message : "mic acquire error"
console.warn(`${LOG_TAG}: mic_acquire failed for ${packageName}:`, message)
this.sendResult(packageName, requestId, false, undefined, {
code: message.startsWith(MIC_SOURCE_CONFLICT)
? MiniappErrorCode.MIC_SOURCE_CONFLICT
: MiniappErrorCode.INTERNAL,
message,
})
}
}
/** session.mic.acquire(...).release() — drop one session, if the caller owns it. */
private handleMicRelease(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const sessionId = payload.sessionId
const entry = typeof sessionId === "number" ? this.micSessionsByApp.get(sessionId) : undefined
if (!entry || entry.packageName !== packageName) {
// Idempotent by design: a miniapp releasing twice, or releasing after unregister already
// dropped its sessions, is not an error worth failing a teardown path over.
this.sendResult(packageName, requestId, true)
return
}
this.micSessionsByApp.delete(entry.session.id)
entry.session.release()
console.log(`${LOG_TAG}: mic_release #${entry.session.id} (by ${packageName})`)
this.sendResult(packageName, requestId, true)
}
/** Drop the bookkeeping for every session an app owns. The manager is the source of truth. */
private forgetMicSessions(packageName: string): void {
for (const [id, entry] of this.micSessionsByApp) {
if (entry.packageName === packageName) this.micSessionsByApp.delete(id)
}
}
/**
* session.system.scanQr — host camera overlay. Must not clear miniapp
* foreground; the host seam is responsible for presenting a Modal on top.
*/
private async handleScanQr(packageName: string, payload: Record<string, unknown>, requestId?: string): Promise<void> {
try {
const result = await invokeScanQrSeam(getUiSeams().scanQr, payload)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
if (!getUiSeams().scanQr) {
console.warn(`${LOG_TAG}: scanQr seam missing — QR overlay is not registered`)
}
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string} | null | undefined)?.code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "QR scan failed",
})
}
}
// ---------------------------------------------------------------------------
// System utilities (share, open URL and download are in MiniappSystemActions)
// ---------------------------------------------------------------------------
private async handleCopyClipboard(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const text = payload.text as string | undefined
if (typeof text !== "string") {
console.warn(`${LOG_TAG}: copy_clipboard missing text`)
return
}
try {
await Clipboard.setStringAsync(text)
this.sendResult(packageName, requestId, true)
} catch (error: any) {
console.error(`${LOG_TAG}: clipboard error:`, error)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error?.message || "Clipboard error",
})
}
}
// ===========================================================================
// Photo + streaming handlers (cloud-coordinated)
// ===========================================================================
/**
* Manifest permission gate shared by the camera-and-mic RPCs (streams, meetings).
* Sends PERMISSION_NOT_DECLARED and returns false when the miniapp did not declare
* `permission`; the caller must return without doing the work.
*/
private requireManifestPermission(
packageName: string,
requestId: string | undefined,
permission: "CAMERA" | "PHONE_CAMERA" | "MICROPHONE",
purpose: string,
operation: MiniappRequestType,
): boolean {
const app = this.connectedApps.get(packageName)
if (app?.installedManifest?.permissions?.some((p) => p.type === permission)) return true
logPermissionNotDeclared(packageName, permission, purpose, `{"type": "${permission}"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `${permission} permission not declared in miniapp.json. Add {"type": "${permission}"} to the "permissions" array.`,
permission,
operation,
})
return false
}
/**
* OS-permission gate: checked, never requested.
*
* The prompt belongs at miniapp-open time, where it can be explained. Requesting here would put
* a system dialog on top of a join that has already started building a hotspot, and a wearer who
* denies it gets a call that half-exists. Missing means the join is refused with the permission
* named, so the miniapp can send them to Settings.
*/
private async requireOsPermission(
packageName: string,
requestId: string | undefined,
feature: string,
label: string,
): Promise<boolean> {
if (await permissions.check(feature)) return true
softapTraceFailure("softap_permission_missing", {packageName, feature})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: `This phone's ${label} permission is not granted. Grant it in Settings, then try again.`,
permission: feature,
operation: MiniappRequestType.MEETING_JOIN,
})
return false
}
private async handlePhoto(packageName: string, payload: Record<string, unknown>, requestId?: string): Promise<void> {
// Manifest CAMERA permission gate.
const app = this.connectedApps.get(packageName)
const hasCameraPermission = app?.installedManifest?.permissions?.some((p) => p.type === "CAMERA")
if (!hasCameraPermission) {
logPermissionNotDeclared(packageName, "CAMERA", "to take a photo", `{"type": "CAMERA"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `CAMERA permission not declared in miniapp.json. Add {"type": "CAMERA"} to the "permissions" array.`,
permission: "CAMERA",
operation: MiniappRequestType.PHOTO,
})
return
}
try {
const result = await phonePhotoCoordinator.takePhoto(packageName, {
size: payload.size as "low" | "medium" | "high" | "max" | "small" | "large" | "full" | undefined,
mode: payload.mode as "photo" | "text" | undefined,
transferMethod: payload.transferMethod as "auto" | "direct" | "ble" | undefined,
compress: parsePhotoCompression(payload.compress),
sound: payload.sound as boolean | undefined,
saveToGallery: payload.saveToGallery as boolean | undefined,
exposureTimeNs: payload.exposureTimeNs as number | undefined,
iso: payload.iso as number | null | undefined,
aeExposureDivisor: payload.aeExposureDivisor as number | undefined,
isoCap: payload.isoCap as number | undefined,
noiseReduction: payload.noiseReduction as boolean | undefined,
edgeEnhancement: payload.edgeEnhancement as boolean | undefined,
zsl: payload.zsl as boolean | undefined,
mfnr: payload.mfnr as boolean | undefined,
ispDigitalGain: payload.ispDigitalGain as number | undefined,
ispAnalogGain: payload.ispAnalogGain as string | undefined,
})
this.sendResult(packageName, requestId, true, result)
// The photo reached the miniapp. A call with no request ID has nobody to answer, so nothing was delivered.
if (requestId) fleetEvents.photo({operationId: result.requestId, stage: "delivered"})
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Photo request failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleCameraWarmUp(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
// Manifest CAMERA permission gate (same as photo).
const app = this.connectedApps.get(packageName)
const hasCameraPermission = app?.installedManifest?.permissions?.some((p) => p.type === "CAMERA")
if (!hasCameraPermission) {
logPermissionNotDeclared(packageName, "CAMERA", "to warm up the camera", `{"type": "CAMERA"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `CAMERA permission not declared in miniapp.json. Add {"type": "CAMERA"} to the "permissions" array.`,
permission: "CAMERA",
operation: MiniappRequestType.CAMERA_WARM_UP,
})
return
}
try {
await phonePhotoCoordinator.warmUpCamera(packageName, {
size: payload.size as "low" | "medium" | "high" | "max" | undefined,
mode: payload.mode as "photo" | "text" | undefined,
exposureTimeNs: payload.exposureTimeNs as number | undefined,
durationMs: payload.durationMs as number | undefined,
zsl: payload.zsl as boolean | undefined,
mfnr: payload.mfnr as boolean | undefined,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Camera warm-up failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleVideoRecordingStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
// Manifest CAMERA permission gate (same as photo).
const app = this.connectedApps.get(packageName)
const hasCameraPermission = app?.installedManifest?.permissions?.some((p) => p.type === "CAMERA")
if (!hasCameraPermission) {
logPermissionNotDeclared(packageName, "CAMERA", "to record video", `{"type": "CAMERA"}`)
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_NOT_DECLARED,
message: `CAMERA permission not declared in miniapp.json. Add {"type": "CAMERA"} to the "permissions" array.`,
permission: "CAMERA",
operation: MiniappRequestType.VIDEO_RECORDING_START,
})
return
}
try {
const result = await phoneVideoCoordinator.startRecording(packageName, {
width: payload.width as number | undefined,
height: payload.height as number | undefined,
fps: payload.fps as number | undefined,
sound: payload.sound as boolean | undefined,
save: payload.save as boolean | undefined,
})
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Video recording start failed",
})
}
}
private async handleVideoRecordingStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
await phoneVideoCoordinator.stopRecording(packageName, payload.recordingId as string | undefined, {
uploadUrl: payload.uploadUrl as string | undefined,
uploadAuthToken: payload.uploadAuthToken as string | undefined,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Video recording stop failed",
})
}
}
/**
* Stream handlers — dispatched to PhoneStreamCoordinator on the phone.
* Managed streams also use Cloud V2 REST calls to provision resources,
* poll ingest status, and tear down the managed stream. Miniapp JavaScript
* runs locally in the Mentra App.
*/
private async handleStreamStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streaming = phoneStreamCoordinator
if (!streaming) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Streaming is not configured on this host",
})
return
}
// A stream is the glasses camera (and mic) leaving the device; gate it like a photo.
if (
!this.requireManifestPermission(
packageName,
requestId,
"CAMERA",
"to stream the camera",
MiniappRequestType.STREAM_START,
)
) {
return
}
try {
const result = await streaming.startUnmanaged(packageName, {
streamUrl: payload.streamUrl as string,
video: normalizeStreamVideoConfig(payload.video),
audio: normalizeStreamAudioConfig(payload.audio),
sound: payload.sound as boolean | undefined,
authToken: typeof payload.authToken === "string" ? payload.authToken : undefined,
captureAudio: resolveCaptureAudio(payload.captureAudio, resolveAcsAudioSource().source),
})
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Stream start failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleStreamStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streaming = phoneStreamCoordinator
if (!streaming) {
// No adapter wired — treat as already-stopped.
this.sendResult(packageName, requestId, true)
return
}
try {
await streaming.stop(packageName, payload.streamId as string | undefined)
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Stream stop failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleManagedStreamStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const streaming = phoneStreamCoordinator
if (!streaming) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Streaming is not configured on this host",
})
return
}
if (
!this.requireManifestPermission(
packageName,
requestId,
"CAMERA",
"to stream the camera",
MiniappRequestType.MANAGED_STREAM_START,
)
) {
return
}
try {
if (payload.ingest === "whip" && !(await permissions.check(PermissionFeatures.LOCAL_WIFI))) {
if (!(await permissions.request(PermissionFeatures.LOCAL_WIFI))) {
throw new Error("Nearby devices permission is required to join the glasses hotspot")
}
}
const result = await streaming.startManaged(packageName, {
restreamDestinations: payload.restreamDestinations as Array<string | {url: string; name?: string}> | undefined,
video: normalizeStreamVideoConfig(payload.video),
audio: normalizeStreamAudioConfig(payload.audio),
sound: payload.sound as boolean | undefined,
ingest: payload.ingest as "srt" | "whip" | "rtmp" | undefined,
captureAudio: normalizeCaptureAudio(payload.captureAudio),
})
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Managed stream start failed",
stage: (err as {stage?: string}).stage,
transport: (err as {transport?: string}).transport,
})
}
}
private async handleManagedStreamStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
return this.handleStreamStop(packageName, payload, requestId)
}
/** True when the installed manifest of a connected miniapp declares `permission`. */
public hasManifestPermission(packageName: string, permission: string): boolean {
return (
this.connectedApps.get(packageName)?.installedManifest?.permissions?.some((p) => p.type === permission) ?? false
)
}
/**
* Raw decoded-frame preview lease. Authorization, the single-holder rule and the lease's
* lifetime live in the host coordinator; the runtime supplies identity and delivery.
*/
private async handleStreamPreviewStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const previewHost = getStreamPreviewHost()
if (!app || !previewHost) {
this.sendResult(packageName, requestId, false, undefined, {
code: "unsupported",
message: "Stream preview is not available in this Mentra App",
})
return
}
const runtimeId = app.runtimeId
try {
const result = await previewHost.start(
{packageName, runtimeId, source: payload.source, hasCamera: this.hasManifestPermission(packageName, "CAMERA")},
(event) => {
// A respawned background must not hear about its predecessor's lease.
if (this.connectedApps.get(packageName)?.runtimeId !== runtimeId) return
this.sendToMiniapp(packageName, {type: MiniappResponseType.STREAM_PREVIEW_STATUS, ...event})
},
)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
const code = (err as {code?: unknown}).code
this.sendResult(packageName, requestId, false, undefined, {
code: typeof code === "string" ? code : "unsupported",
message: err instanceof Error ? err.message : "Stream preview failed",
})
}
}
private async handleStreamPreviewStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const app = this.connectedApps.get(packageName)
const previewHost = getStreamPreviewHost()
if (app && previewHost && typeof payload.handleId === "string") {
try {
await previewHost.stop({packageName, runtimeId: app.runtimeId, handleId: payload.handleId})
} catch (err) {
console.warn(`${LOG_TAG}: stream preview stop failed for ${packageName}`, err)
}
}
// Releasing is idempotent from the miniapp's side: an unknown or stale handle is already gone.
this.sendResult(packageName, requestId, true)
}
private ensureMeetingStateBridge(): void {
acsMeetingService.setPhotoPauseExpiredHandler((pauseId) => {
const owner = acsMeetingService.ownerPackage()
if (owner) this.notifyPhotoPauseExpired(owner, pauseId)
})
acsMeetingService.setStateHandler((owner, state) => {
const attempt = this.softapAttempt
// While a replacement waits for cleanup, native events still describe its predecessor.
if (attempt?.packageName === owner && !attempt.ownsResources) return
this.sendToMiniapp(owner, {
type: MiniappResponseType.MEETING_STATE,
...state,
...this.softapRecoveryFields(attempt?.packageName === owner ? attempt : null),
})
if (attempt?.ownsResources && attempt.transport?.shouldRepublish(state.mediaSource)) {
void attempt.transport.republish(state.mediaSourceReason ?? "mediaSource failed")
}
})
}
/** Startup owns the hotspot before ACS has an owner. Closing the app must retire both. */
private readonly meetingCredentialRequests = new Map<string, object>()
private async handleMeetingIdentity(packageName: string, requestId?: string): Promise<void> {
try {
this.sendResult(packageName, requestId, true, await meetingIdentity())
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Could not check the meeting identity",
})
}
}
private async handleMeetingCreate(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
// Provider credentials and organizer IDs are host-owned, never copied from the RPC.
const result = await createMeeting({
provider: payload.provider as "acs-teams",
subject: payload.subject as string | undefined,
durationMinutes: payload.durationMinutes as number | undefined,
})
this.sendResult(packageName, requestId, true, result)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Meeting creation failed",
})
}
}
private async handleMeetingRetire(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
await retireMeeting(payload.meetingRef as string)
this.sendResult(packageName, requestId, true)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Meeting retirement failed",
})
}
}
private async leaveMeetingForApp(packageName: string): Promise<void> {
this.meetingCredentialRequests.delete(packageName)
const attempt = this.softapAttempt
if (attempt?.packageName === packageName) {
await this.retireSoftapAttempt({attempt})
} else {
await acsMeetingService.leaveIfOwner(packageName)
}
}
private async handleMeetingJoin(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const credentialRequest = {}
this.meetingCredentialRequests.set(packageName, credentialRequest)
if (!meetingConfiguration().enabled) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.PERMISSION_DENIED,
message: "Native meetings are disabled by this deployment",
})
return
}
this.ensureMeetingStateBridge()
// A meeting puts the glasses camera and mic in front of remote strangers; it
// needs both declared, same as photo/stream and mic capture do individually.
if (
!this.requireManifestPermission(
packageName,
requestId,
"CAMERA",
"to join a meeting",
MiniappRequestType.MEETING_JOIN,
) ||
!this.requireManifestPermission(
packageName,
requestId,
"MICROPHONE",
"to join a meeting",
MiniappRequestType.MEETING_JOIN,
) ||
!this.requireManifestPermission(
packageName,
requestId,
"PHONE_CAMERA",
"to join a meeting",
MiniappRequestType.MEETING_JOIN,
)
) {
return
}
// Defensive only: these are prompted for when the wearer opens the miniapp, so by the time a
// join runs they are either granted or were refused minutes ago on a screen that explained
// them. Checked and never requested — a permission dialog on top of a half-built call is
// asked too late to explain itself, and ACS fails the join outright without the camera.
if (!(await this.requireOsPermission(packageName, requestId, PermissionFeatures.CAMERA, "camera"))) return
if (!(await this.requireOsPermission(packageName, requestId, PermissionFeatures.MICROPHONE, "microphone"))) return
// The wearer's voice rides a microphone session, not the meeting. An app allowed to make voice
// calls must hold one before the sink starts, or it would get a call configured for dictation.
// Other joiners are not required to: without a session the BLE LC3 uplink is simply not
// selected and the audio rides the WHIP capture path, exactly as it did before.
const glassesSession = micSessionManager.hasGlassesSession(packageName)
if (VOICE_CALL_PACKAGES.includes(packageName) && !glassesSession) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.MIC_SESSION_REQUIRED,
message: "acquire a glasses microphone session before joining a meeting",
})
return
}
const meetingUrl = typeof payload.meetingUrl === "string" ? payload.meetingUrl : ""
const legacyToken = typeof payload.token === "string" ? payload.token : undefined
const displayName = typeof payload.displayName === "string" ? payload.displayName : undefined
// Diagnostic only. A miniapp that does not send it gets `unknown`, which is a third answer in
// the comparison rather than a default that would quietly file every old build under "created".
const origin = parseAcsCallOrigin(payload.origin)
if (!meetingUrl) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "meetingUrl is required",
})
return
}
let videoSource: AcsVideoSource
try {
videoSource = parseAcsVideoSource(payload.videoSource)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: error instanceof Error ? error.message : "Invalid meeting video source",
})
return
}
try {
let video: ReturnType<typeof parseAcsOutgoingVideo>
try {
video = parseAcsOutgoingVideo(payload.video)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: error instanceof Error ? error.message : "Invalid meeting video",
})
return
}
const configuration = meetingConfiguration()
if (!configuration.externalBackendAllowed && videoSource.type !== "softap") {
throw new Error("Private meetings require direct glasses video")
}
const credential = await meetingCredential(legacyToken)
if (this.meetingCredentialRequests.get(packageName) !== credentialRequest) {
throw new Error("Meeting join was cancelled")
}
const {token, identityMode, guestReason} = credential
const identity: MeetingIdentity = {identityMode, guestReason}
// SoftAP is a sequence, not a single call: the hotspot and the scoped network have to exist
// before the ACS join binds a listener, and the glasses can only be told where to publish
// after that. The miniapp asks for the transport and the host owns the ordering.
if (videoSource.type === "softap") {
// The miniapp's `requestId` is the only identifier the two logs share until the attempt
// exists, so it is what joins the miniapp's own join line to the host's.
softapTrace("meeting_join_request", {
packageName,
requestId: requestId ?? "none",
transport: videoSource.type,
hasDisplayName: Boolean(displayName),
video: video ? `${video.width}x${video.height}@${video.fps}` : "default",
origin,
})
const startedAt = Date.now()
try {
const state = await this.joinSoftapMeeting(packageName, {
meetingUrl,
token,
identity,
displayName,
video,
origin,
glassesSession,
})
softapTrace("meeting_join_result", {
packageName,
requestId: requestId ?? "none",
state: state.state,
micTransport: state.micTransport ?? "unknown",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true, state)
} catch (error) {
softapTraceFailure("meeting_join_result", {
packageName,
requestId: requestId ?? "none",
step: error instanceof SoftapCallError ? error.step : "unknown",
code: error instanceof SoftapCallError ? error.code : "INTERNAL",
reason: error instanceof Error ? error.message : String(error),
durationMs: Date.now() - startedAt,
})
throw error
}
return
}
const state = await acsMeetingService.join(packageName, {
meetingUrl,
token,
identity,
videoSource,
displayName,
origin,
glassesSession,
...(video ? {video} : {}),
})
this.sendResult(packageName, requestId, true, state)
} catch (err) {
// A SoftAP failure already knows what it was and where. Flattening every one of them to
// INTERNAL is what left the miniapp unable to tell "your Wi-Fi is off" — a condition with a
// two-tap fix — from an ACS timeout, so it showed the same shrug for both. The step comes
// along too: the same code at `hotspot` and at `scopedJoin` are different stories.
const softap = err instanceof SoftapCallError ? err : undefined
this.sendResult(packageName, requestId, false, undefined, {
code: softap?.code ?? MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS meeting join failed",
...(softap ? {step: softap.step} : {}),
})
}
}
/**
* Runs the SoftAP call sequence and returns the meeting state it reached.
*
* Everything is hung off one [SoftapAttempt] registered before the first `await`, because the
* cancellable part of this starts immediately and the transport only exists halfway through.
* The attempt is also what `meeting.leave` unwinds: leaving only the ACS call would strand the
* glasses publishing into a listener nobody reads, the phone on a hotspot it no longer needs,
* and this process pinned to cellular.
*/
private async joinSoftapMeeting(
packageName: string,
args: {
meetingUrl: string
token: string
identity?: MeetingIdentity
displayName?: string
video?: AcsOutgoingVideo
origin?: AcsCallOrigin
glassesSession: boolean
},
): Promise<MeetingState> {
// Reserve before awaiting retirement: a second Start or Cancel must see this request,
// including while it is waiting for its predecessor's native cleanup.
const previous = this.softapAttempt
const attempt = this.createSoftapAttempt(packageName)
this.softapAttempt = attempt
const body = this.runSoftapAttempt(attempt, previous, args)
// Settled, never rejected: this exists so the *next* attempt can tell when this one's native
// work has actually stopped, and a rejection here is already handled below.
attempt.body = body.then(
() => undefined,
() => undefined,
)
try {
return await body
} catch (error) {
softapTraceFailure("softap_attempt_failed", {
attempt: attempt.id,
step: error instanceof SoftapCallError ? error.step : "unknown",
code: error instanceof SoftapCallError ? error.code : "INTERNAL",
reason: error instanceof Error ? error.message : String(error),
attemptAgeMs: Date.now() - attempt.startedAt,
})
// Unwind whatever the attempt reached — including the preflight-owned agent and cellular
// pin, which the transport never sees — before the failure surfaces.
await this.retireSoftapAttempt({attempt}).catch(() => undefined)
throw error
}
}
private createSoftapAttempt(packageName: string): SoftapAttempt {
const id = ++this.softapAttemptSeq
let resolveSettled!: () => void
const settled = new Promise<void>((resolve) => {
resolveSettled = resolve
})
const attempt: SoftapAttempt = {
id,
packageName,
startedAt: Date.now(),
cancelled: false,
ownsResources: false,
transport: null,
progress: {
traceId: `preflight-${id}`,
phase: "starting",
steps: SOFTAP_STEPS.map((step) => ({step, status: "pending" as const})),
elapsedMs: 0,
mediaGeneration: 0,
},
scopedLostUnsub: null,
recovery: null,
recoveryActive: false,
recoveryDeadlineAt: null,
body: null,
teardown: null,
settled,
settledDone: false,
markSettled: () => {
if (attempt.settledDone) return
attempt.settledDone = true
softapTrace("softap_attempt_settled", {attempt: id, attemptAgeMs: Date.now() - attempt.startedAt})
resolveSettled()
},
}
softapTrace("softap_attempt_created", {attempt: id, packageName})
return attempt
}
/**
* Throws if this attempt has been cancelled or superseded.
*
* Called after every `await` in the join. The wearer's Cancel cannot interrupt a native call
* that is already in flight, so the next best thing — and the thing that actually makes Cancel
* work — is to refuse to take another step once they have asked.
*
* @param after the await this checkpoint follows. The whole join surfaces as one CANCELLED
* error, so without a name in the log there is no way to tell a Cancel during the permission
* prompt from one during a 35-second Teams sign-in.
*/
private checkpointSoftapAttempt(attempt: SoftapAttempt, after: string): void {
if (attempt.cancelled || this.softapAttempt !== attempt) {
softapTraceFailure("softap_attempt_cancelled", {
attempt: attempt.id,
after,
attemptAgeMs: Date.now() - attempt.startedAt,
// Two different causes with one outcome: the wearer asked to leave, or a second join
// took the slot. They need different fixes, so they are not collapsed here.
cause: attempt.cancelled ? "retired" : "superseded",
current: this.softapAttempt?.id ?? "none",
})
throw new SoftapCallError("hotspot", "CANCELLED", "The call was cancelled while it was starting")
}
}
/** Publishes a checklist snapshot, unless this attempt has already been superseded. */
private emitSoftapProgress(attempt: SoftapAttempt, progress: SoftapProgress): void {
if (this.softapAttempt !== attempt || attempt.cancelled) {
// A dropped checklist is why a stalled join used to look like a stuck UI: the wearer's last
// row was written by an attempt that no longer owned the call, and nothing said so.
softapTrace("softap_progress_dropped", {
attempt: attempt.id,
phase: progress.phase,
traceId: progress.traceId,
cause: attempt.cancelled ? "retired" : "superseded",
current: this.softapAttempt?.id ?? "none",
})
return
}
attempt.progress = progress
// A reservation waiting behind another call must not inherit that call's connected state.
const current = attempt.transport ? acsMeetingService.getState() : {state: "connecting", muted: false}
this.sendToMiniapp(attempt.packageName, {
type: MiniappResponseType.MEETING_STATE,
...current,
// Before the ACS join there is no native state yet, so the phase reads `connecting`: the
// join *is* in progress, and `idle` would make the miniapp think the call ended.
state: current.state === "idle" ? "connecting" : current.state,
softap: progress,
...this.softapRecoveryFields(attempt),
})
}
private softapRecoveryFields(attempt: SoftapAttempt | null | undefined): {
recovery?: {
active: boolean
generation?: number
deadlineAt?: number
phase?: string
}
} {
if (!attempt?.recoveryDeadlineAt) return {}
return {
recovery: {
active: attempt.recoveryActive,
generation: attempt.transport?.currentMediaGeneration(),
deadlineAt: attempt.recoveryDeadlineAt,
phase: attempt.transport?.currentPhase(),
},
}
}
/**
* Narrates preflight work on the first row while it is still pending.
*
* Permissions, mobile data, and the ACS sign-in take most of a minute between them and happen
* before the transport exists, so without this the wearer watches five pending rows and
* concludes the app has hung. No new step and no protocol change: it is the `hotspot` row's
* detail, which the connecting screen renders as its one sub-line until step 1 starts.
*/
private narrateSoftapPreflight(attempt: SoftapAttempt, detail: string): void {
this.emitSoftapProgress(attempt, {
...attempt.progress,
elapsedMs: Date.now() - attempt.startedAt,
steps: attempt.progress.steps.map((step) => (step.step === "hotspot" ? {...step, detail} : step)),
})
}
private async runSoftapAttempt(
attempt: SoftapAttempt,
previous: SoftapAttempt | null,
args: {
meetingUrl: string
token: string
identity?: MeetingIdentity
displayName?: string
video?: AcsOutgoingVideo
origin?: AcsCallOrigin
glassesSession: boolean
},
): Promise<MeetingState> {
const packageName = attempt.packageName
if (previous) {
this.narrateSoftapPreflight(attempt, "Finishing the previous call’s cleanup…")
softapTrace("softap_join_superseding", {
previousAttempt: previous.id,
previousAgeMs: Date.now() - previous.startedAt,
previousPhase: previous.progress.phase,
packageName,
})
await this.retireSoftapAttempt({attempt: previous}).catch(() => undefined)
await awaitCleanupBarrier({
settled: previous.settled,
settledDone: previous.settledDone,
narrate: (detail) => this.narrateSoftapPreflight(attempt, detail),
narrateAfterMs: SOFTAP_CLEANUP_NARRATE_AFTER_MS,
attempt: attempt.id,
waitingFor: `attempt ${previous.id} teardown`,
})
}
this.checkpointSoftapAttempt(attempt, "cleanup barrier")
const cleanupError = this.softapCleanupError
if (cleanupError) {
// Cleared on read, so this refuses at most once and the next attempt always gets through —
// which is why the wearer is told to retry rather than to go power-cycle anything. The
// native reason stays in the trace: it names a leaked port, not something they can act on.
this.softapCleanupError = null
softapTraceFailure("softap_join_refused", {packageName, reason: cleanupError})
throw new Error("Previous call cleanup has not finished yet. Please try joining again.")
}
attempt.releaseHotspot = acquireGlassesHotspot()
attempt.ownsResources = true
this.narrateSoftapPreflight(attempt, "Checking the Nearby devices permission…")
const permissionStartedAt = Date.now()
if (!(await permissions.check(PermissionFeatures.LOCAL_WIFI))) {
this.checkpointSoftapAttempt(attempt, "permission check")
softapTrace("softap_permission_prompt", {attempt: attempt.id, permission: "LOCAL_WIFI"})
const granted = await permissions.request(PermissionFeatures.LOCAL_WIFI)
this.checkpointSoftapAttempt(attempt, "permission prompt")
softapTrace("softap_permission_result", {
attempt: attempt.id,
granted,
// The prompt is modal, so this is the wearer's own reaction time and the single largest
// unexplained gap in a first-run join.
durationMs: Date.now() - permissionStartedAt,
})
if (!granted) {
throw new Error("Nearby devices permission is required to join the glasses hotspot")
}
}
this.checkpointSoftapAttempt(attempt, "permissions")
const transport = new SoftapCallTransport({
...createSoftapCallDeps({
packageName,
meetingUrl: args.meetingUrl,
token: args.token,
displayName: args.displayName,
video: args.video,
awaitFirstFrame: (_report, options) => acsMeetingService.waitForFirstFrame(SOFTAP_FIRST_FRAME_MS, options),
waitUntilLive: (timeoutMs) => acsMeetingService.waitUntilMediaLive(timeoutMs),
subsystems: {
setHotspotState: async (enabled) => {
const status = await this.setGlassesHotspotState(enabled)
if (status.state === "enabled") {
return {state: status.state, ssid: status.ssid, password: status.password, localIp: status.localIp}
}
return {state: status.state}
},
isWifiEnabled: async () => {
// A host that cannot answer reports "on" so the preflight stands aside; the native
// throw at scopedJoin is what covers those platforms.
const enabled = await acsMeetingService.isWifiEnabled()
return enabled ?? true
},
joinScopedNetwork: (ssid, passphrase, gateway, report) =>
acsMeetingService.joinScopedNetwork(ssid, passphrase, gateway, report),
leaveScopedNetwork: () => acsMeetingService.leaveScopedNetwork(),
cancelScopedNetworkJoin: () => acsMeetingService.cancelScopedNetworkJoin(),
probeGateway: async () => {
const verdict = await acsMeetingService.probeScopedGateway()
// No native probe means no verdict, and the orchestrator must not read that as "down".
return verdict ?? {reachable: true, detail: "probe unsupported on this host"}
},
awaitValidatedDefaultNetwork: () => acsMeetingService.awaitValidatedDefaultNetwork(),
onGlassesStreamStatus: (listener) => {
const sub = BluetoothSdk.addListener("stream_status", (event) => {
// The glasses narrate over BLE, which is slow enough that a status from the previous
// publish can land after this attempt was retired — and it is narration, so it would
// be written straight onto the new call's checklist as if it were happening now.
if (this.softapAttempt !== attempt || attempt.cancelled) {
softapTrace("softap_stale_callback", {
source: "glasses_stream_status",
attempt: attempt.id,
status: event.status,
current: this.softapAttempt?.id ?? "none",
})
return
}
listener({
status: event.status,
streamId: event.streamId,
reason: "reason" in event && typeof event.reason === "string" ? event.reason : undefined,
error: "error" in event && typeof event.error === "string" ? event.error : undefined,
})
})
return () => sub.remove()
},
joinMeeting: (pkg, options) =>
acsMeetingService.join(pkg, {
meetingUrl: options.meetingUrl,
token: options.token,
identity: args.identity,
videoSource: options.videoSource,
displayName: options.displayName,
origin: args.origin,
glassesSession: args.glassesSession,
...(args.video ? {video: args.video} : {}),
}),
leaveMeeting: (pkg) => acsMeetingService.leave(pkg),
endMeeting: async (pkg) => {
await acsMeetingService.endForEveryone(pkg)
},
ingestUrl: () => acsMeetingService.softApIngestUrl(),
glassesLc3Uplink: () => acsMeetingService.glassesLc3UplinkActive(),
startPublishing: (pkg, options) => phoneStreamCoordinator.startUnmanaged(pkg, options),
stopPublishing: (pkg) => phoneStreamCoordinator.stop(pkg),
discardPendingBleStop: () => phoneStreamCoordinator.discardPendingBleStop(),
rebindIngest: async (report) => {
report?.("Rebinding the glasses video receiver on the hotspot")
const ingestUrl = await acsMeetingService.rebindSoftApIngest()
if (!ingestUrl) throw new Error("the rebound meeting reported no ingest URL")
report?.(`Receiver rebound at ${ingestUrl}`)
return {ingestUrl}
},
},
}),
onPublisherPauseExpired: (pauseId) => {
acsMeetingService.clearPhotoPause(pauseId)
this.notifyPhotoPauseExpired(packageName, pauseId)
},
})
attempt.transport = transport
// A hotspot that vanishes mid-call is a real failure and a normal teardown is not, so both
// guards are checked: the attempt must still be the current one (a stale event from a finished
// call must never touch the next one) and it must not already be terminating. The unsubscribe
// lives on the attempt, so retiring attempt N cannot clear attempt N+1's listener. Teardown
// itself is left to the miniapp's terminal path, which calls `meeting.leave` — one owner.
attempt.scopedLostUnsub = acsMeetingService.onScopedNetworkLost((error) => {
if (this.softapAttempt !== attempt || attempt.cancelled) {
console.log("[LocalMiniappRuntime] scoped loss for a superseded SoftAP call; ignoring", error)
softapTrace("softap_scoped_loss_dropped", {
attempt: attempt.id,
code: error.code,
cause: attempt.cancelled ? "retired" : "superseded",
current: this.softapAttempt?.id ?? "none",
})
return
}
if (transport.isTerminating()) {
console.log("[LocalMiniappRuntime] scoped loss during teardown; expected", error)
softapTrace("softap_scoped_loss_dropped", {attempt: attempt.id, code: error.code, cause: "terminating"})
return
}
console.warn("[LocalMiniappRuntime] SoftAP hotspot lost mid-call", error)
softapTraceFailure("softap_scoped_loss_reported", {
attempt: attempt.id,
code: error.code,
reason: error.message,
attemptAgeMs: Date.now() - attempt.startedAt,
})
this.beginSoftapRecovery(attempt, transport, error)
})
// Sign in on the phone's current internet *before* the glasses hotspot takes DNS. On device,
// createCallAgent after the scoped join timed out at 20s and only finished once SoftAP was
// released. It also waits for validated mobile data, which is why the wearer is told one
// honest thing about the whole window rather than nothing at all.
this.narrateSoftapPreflight(attempt, "Signing in to Teams…")
const prepareStartedAt = Date.now()
softapTrace("softap_prepare_agent_begin", {attempt: attempt.id})
try {
await acsMeetingService.prepareAgent({
token: args.token,
displayName: args.displayName,
identityMode: args.identity?.identityMode,
})
} catch (error) {
softapTraceFailure("softap_prepare_agent_failed", {
attempt: attempt.id,
reason: error instanceof Error ? error.message : String(error),
durationMs: Date.now() - prepareStartedAt,
})
throw error
}
softapTrace("softap_prepare_agent_done", {attempt: attempt.id, durationMs: Date.now() - prepareStartedAt})
this.checkpointSoftapAttempt(attempt, "prepareAgent")
await transport.start({
// What the wearer has been reading for the last minute, so the first snapshot does not
// blank it.
initialSteps: attempt.progress.steps,
// Every transition reaches the miniapp as a meeting-state event carrying the checklist.
onProgress: (progress) => this.emitSoftapProgress(attempt, progress),
})
this.checkpointSoftapAttempt(attempt, "transport.start")
const state = acsMeetingService.getState()
softapTrace("softap_attempt_live", {
attempt: attempt.id,
state: state.state,
micTransport: state.micTransport ?? "unknown",
attemptAgeMs: Date.now() - attempt.startedAt,
})
return state
}
/**
* SoftAP loss is a media outage. Keep ACS, destroy generation N, wait for the glasses,
* then build generation N+1. Duplicate losses do not renew the deadline.
*/
private beginSoftapRecovery(
attempt: SoftapAttempt,
transport: SoftapCallTransport,
error: {code: string; message: string},
): void {
// Gate on the live flag, not the promise: a settled Promise is still truthy, so a second
// walk-away after a successful re-arm was dropped as "in-flight" and the glasses kept
// POSTing WHIP at a hotspot the phone had already left.
if (attempt.recoveryActive) {
softapTrace("softap_recovery_dropped", {attempt: attempt.id, cause: "in-flight"})
return
}
if (attempt.cancelled || this.softapAttempt !== attempt) {
softapTrace("softap_recovery_dropped", {
attempt: attempt.id,
cause: attempt.cancelled ? "retired" : "superseded",
})
return
}
const lostAt = Date.now()
attempt.recoveryDeadlineAt = lostAt + RETURN_DEADLINE_MS
attempt.recoveryActive = true
this.emitSoftapProgress(attempt, transport.progress())
softapTrace("softap_recovery_begin", {
attempt: attempt.id,
deadlineAt: attempt.recoveryDeadlineAt,
mediaGeneration: transport.currentMediaGeneration(),
reason: error.message,
})
let run!: Promise<void>
run = (async () => {
try {
await transport.recover(`${error.code}: ${error.message}`, {
wait: async () => {
const remaining = (attempt.recoveryDeadlineAt ?? 0) - Date.now()
if (remaining <= 0) {
throw new SoftapCallError("hotspot", "RETURN_DEADLINE", "The glasses did not return in time")
}
const ready = await this.waitForGlassesReturn(remaining, () => attempt.cancelled)
if (attempt.cancelled || this.softapAttempt !== attempt) {
throw new SoftapCallError("hotspot", "CANCELLED", "SoftAP recovery was cancelled")
}
if (!ready) {
throw new SoftapCallError("hotspot", "RETURN_DEADLINE", "The glasses did not return in time")
}
},
})
if (attempt.cancelled || this.softapAttempt !== attempt) return
this.emitSoftapProgress(attempt, transport.progress())
const current = acsMeetingService.getState()
this.sendToMiniapp(attempt.packageName, {
type: MiniappResponseType.MEETING_STATE,
...current,
softap: transport.progress(),
...this.softapRecoveryFields(attempt),
})
softapTrace("softap_recovery_live", {
attempt: attempt.id,
mediaGeneration: transport.currentMediaGeneration(),
elapsedMs: Date.now() - lostAt,
})
} catch (recoveryError) {
if (attempt.cancelled || this.softapAttempt !== attempt) return
const message = recoveryError instanceof Error ? recoveryError.message : String(recoveryError)
softapTraceFailure("softap_recovery_failed", {
attempt: attempt.id,
reason: message,
elapsedMs: Date.now() - lostAt,
})
const current = acsMeetingService.getState()
this.sendToMiniapp(attempt.packageName, {
type: MiniappResponseType.MEETING_STATE,
...current,
state: "error",
error: `SOFTAP_NETWORK_LOST: ${error.message}`,
softap: transport.progress(),
recovery: {
active: false,
generation: transport.currentMediaGeneration(),
deadlineAt: attempt.recoveryDeadlineAt ?? undefined,
phase: transport.currentPhase(),
},
})
} finally {
attempt.recoveryActive = false
if (attempt.recovery === run) attempt.recovery = null
}
})()
attempt.recovery = run
}
/**
* Wait for a link the hotspot commands can actually use.
*
* The hotspot goes away a couple of seconds before the phone declares the BLE link dead, so the
* snapshot at loss time still reads "ready". Taking that at face value sent `set_hotspot_state`
* into a dying link twice, and each one burned its full timeout before the wearer was even back.
* Requiring the link to hold steady turns that into waiting, which is what the budget is for.
*/
private async waitForGlassesReturn(timeoutMs: number, cancelled: () => boolean): Promise<boolean> {
const deadlineAt = Date.now() + timeoutMs
while (!cancelled()) {
const remaining = deadlineAt - Date.now()
if (remaining <= 0) return false
if (
!isGlassesReady(useGlassesStore.getState().connection) &&
!(await this.awaitGlassesReady(remaining, cancelled))
) {
return false
}
const settleMs = Math.min(GLASSES_LINK_SETTLE_MS, Math.max(0, deadlineAt - Date.now()))
if (await this.glassesLinkHoldsSteady(settleMs, cancelled)) return true
}
return false
}
private awaitGlassesReady(timeoutMs: number, cancelled: () => boolean): Promise<boolean> {
const controller = new AbortController()
const poll = setInterval(() => {
if (cancelled()) controller.abort()
}, 250)
return waitForGlassesReady({
getConnection: () => useGlassesStore.getState().connection,
subscribe: (listener) => useGlassesStore.subscribe((state) => state.connection, listener),
timeoutMs,
signal: controller.signal,
}).finally(() => clearInterval(poll))
}
/** True when the link stays ready for [ms]; false the moment it drops again. */
private glassesLinkHoldsSteady(ms: number, cancelled: () => boolean): Promise<boolean> {
if (ms <= 0) return Promise.resolve(isGlassesReady(useGlassesStore.getState().connection))
return new Promise<boolean>((resolve) => {
let done = false
const settle = (steady: boolean) => {
if (done) return
done = true
clearTimeout(timer)
clearInterval(poll)
unsubscribe()
resolve(steady)
}
const unsubscribe = useGlassesStore.subscribe(
(state) => state.connection,
(connection) => {
if (!isGlassesReady(connection)) settle(false)
},
)
const poll = setInterval(() => {
if (cancelled()) settle(false)
}, 250)
const timer = setTimeout(() => settle(true), ms)
})
}
/**
* Cancels a SoftAP attempt and does not return until everything it owns has been released.
*
* This is the barrier the whole design rests on: "leave returned" has to mean "nothing from that
* call is still in flight", or the next Start races the previous call's cleanup through the same
* hotspot. There is deliberately no deadline — a native call that never returns holds the next
* call back rather than letting it race — and a watchdog only says so in the log.
*
* Safe to call when there is no attempt, and safe to call twice: the teardown is single-flight
* per attempt, so a leave and the join's own failure path share one unwind.
*/
private async retireSoftapAttempt(options: {attempt?: SoftapAttempt; mode?: SoftapTeardownMode} = {}): Promise<void> {
const attempt = options.attempt ?? this.softapAttempt
if (!attempt) {
// Not an error — every terminal path calls this without checking — but a Leave that found
// nothing to retire and a Leave that tore a call down are very different log entries.
softapTrace("softap_retire_noop", {mode: options.mode ?? "leave"})
return
}
attempt.cancelled = true
// Keep the retiring attempt discoverable until both its join and cleanup settle.
// A newer reservation replaces it immediately, but must still wait on its barrier.
softapTrace("softap_retire_begin", {
attempt: attempt.id,
mode: options.mode ?? "leave",
attemptAgeMs: Date.now() - attempt.startedAt,
phase: attempt.progress.phase,
// Second and later callers join the first one's teardown rather than running their own, and
// that sharing is what makes a leave racing a failed join safe.
teardownAlreadyRunning: Boolean(attempt.teardown),
})
if (!attempt.teardown) {
attempt.teardown = this.teardownSoftapAttempt(attempt, options.mode)
// The barrier closes over the join body as well as the teardown, and opens only when both
// have stopped. A watchdog reports a cleanup that is taking too long; it never declares one
// finished, because "probably done by now" is exactly the assumption that broke restarts.
const stallWatchdog = setTimeout(() => {
console.warn("[LocalMiniappRuntime] softap_cleanup_stalled", {
attempt: attempt.id,
afterMs: SOFTAP_CLEANUP_STALL_LOG_MS,
})
}, SOFTAP_CLEANUP_STALL_LOG_MS)
void Promise.allSettled([
attempt.teardown,
attempt.body ?? Promise.resolve(),
attempt.recovery ?? Promise.resolve(),
]).then(() => {
clearTimeout(stallWatchdog)
attempt.markSettled()
if (this.softapAttempt === attempt) this.softapAttempt = null
})
}
const awaitedFrom = Date.now()
try {
await attempt.teardown
} catch (error) {
// Only a refused End reaches here; the local unwind has completed either way, which is the
// distinction the wearer's copy depends on.
softapTraceFailure("softap_retire_done", {
attempt: attempt.id,
waitedMs: Date.now() - awaitedFrom,
reason: error instanceof Error ? error.message : String(error),
})
throw error
}
softapTrace("softap_retire_done", {attempt: attempt.id, waitedMs: Date.now() - awaitedFrom})
}
/**
* Releases everything one attempt could own, in the reverse of the order it was taken.
*
* The scoped network and the ACS agent are released unconditionally, not only when the transport
* built them: `prepareAgent` signs in and pins this whole process to cellular *before* the
* transport exists, so a Cancel during sign-in would otherwise leave both behind. Both releases
* are idempotent.
*
* Failures are collected rather than swallowed. Reporting a clean teardown that did not happen
* is what lets the next call start on leaked state.
*/
private async teardownSoftapAttempt(attempt: SoftapAttempt, mode?: SoftapTeardownMode): Promise<void> {
// A cancelled reservation waiting behind another call never acquired any shared resources.
// Its cleanup must not release the preceding call's native agent or network.
if (!attempt.ownsResources) return
// Terminal intent before the first release, so the scoped network we are about to drop cannot
// be reported as a hotspot that walked away.
acsMeetingService.beginScopedTeardown()
const failures: string[] = []
let endFailure: unknown = null
const teardownStartedAt = Date.now()
softapTrace("softap_teardown_begin", {
attempt: attempt.id,
mode: mode ?? "leave",
hasTransport: Boolean(attempt.transport),
steps: attempt.transport?.activeSteps().join(",") ?? "",
})
/**
* One line per resource, whether it released or not.
*
* The releases below are sequential and every one of them can block on a native call, so a
* teardown that takes half a minute is only readable if each step says how long it took. A
* step that never reports is the one that hung.
*/
const releaseStep = async (step: string, release: () => Promise<void>): Promise<unknown> => {
const startedAt = Date.now()
try {
await release()
softapTrace("softap_teardown_step", {
attempt: attempt.id,
step,
outcome: "ok",
durationMs: Date.now() - startedAt,
})
return null
} catch (error) {
softapTraceFailure("softap_teardown_step", {
attempt: attempt.id,
step,
outcome: "failed",
durationMs: Date.now() - startedAt,
reason: error instanceof Error ? error.message : String(error),
})
return error
}
}
const transport = attempt.transport
if (transport) {
// The only thing `stop()` throws is a refused End — the local teardown still completed,
// so this is the caller's business, not a reason to block the next call.
endFailure = await releaseStep("transport.stop", () => transport.stop(mode ? {mode} : {}))
const undoFailures = transport.lastTeardownFailures()
// A hotspot that did not ACK off is leftover ON — the next join wants it on and will
// call setHotspotState(true). Refusing that join is how we got hotspot_off_ack_timeout
// as a wearer-facing "power-cycle the glasses" dead end.
const blockingUndos = undoFailures.filter((step) => step !== "hotspot")
if (blockingUndos.length > 0) failures.push(`could not release ${blockingUndos.join(", ")}`)
if (undoFailures.includes("hotspot")) {
console.warn("[LocalMiniappRuntime] glasses hotspot undo timed out; next join will raise it again", {
attempt: attempt.id,
})
}
}
const scopedFailure = await releaseStep("leaveScopedNetwork", () => acsMeetingService.leaveScopedNetwork())
if (scopedFailure) {
failures.push(
`leaveScopedNetwork: ${scopedFailure instanceof Error ? scopedFailure.message : String(scopedFailure)}`,
)
}
// Stay pinned across this wait. Unpinning onto a leftover glasses AP is what made the next
// Start Call's `teams:create` return `Request failed (503)` — Cloudflare, no internet, not a
// Teams configuration problem.
const defaultNetworkStartedAt = Date.now()
let defaultNetworkOk = false
try {
const network = await acsMeetingService.awaitDefaultNetworkAfterHotspot()
defaultNetworkOk = true
softapTrace("softap_teardown_step", {
attempt: attempt.id,
step: "awaitValidatedDefaultNetwork",
outcome: "ok",
durationMs: Date.now() - defaultNetworkStartedAt,
// Null is "this host cannot tell", which is a different fact from an unusable route, and
// the cellular pin is dropped on the strength of this answer.
network: network?.detail ?? "unknown",
usable: network?.usable ?? "unknown",
})
} catch (error) {
console.warn("[LocalMiniappRuntime] default network after SoftAP teardown is unverified", {
attempt: attempt.id,
error: error instanceof Error ? error.message : String(error),
})
softapTraceFailure("softap_teardown_step", {
attempt: attempt.id,
step: "awaitValidatedDefaultNetwork",
outcome: "failed",
durationMs: Date.now() - defaultNetworkStartedAt,
reason: error instanceof Error ? error.message : String(error),
})
}
const defaultNetworkMs = Date.now() - defaultNetworkStartedAt
const acsLeaveStartedAt = Date.now()
let acsLeaveOk = false
try {
const outcome = await acsMeetingService.leaveAndAwait(attempt.packageName)
acsLeaveOk = outcome.completed
softapTrace("softap_teardown_step", {
attempt: attempt.id,
step: "acsLeaveAndAwait",
// `completed=false` is not a failure and is not recorded as one: the build simply cannot
// confirm its own cleanup, so the next call's barrier is the only guarantee left.
outcome: outcome.completed ? "ok" : "unconfirmed",
reason: outcome.reason ?? "",
durationMs: Date.now() - acsLeaveStartedAt,
})
if (!outcome.completed) {
console.warn("[LocalMiniappRuntime] ACS cleanup completion is unverified on this build", {
attempt: attempt.id,
reason: outcome.reason,
})
}
} catch (error) {
softapTraceFailure("softap_teardown_step", {
attempt: attempt.id,
step: "acsLeaveAndAwait",
outcome: "failed",
durationMs: Date.now() - acsLeaveStartedAt,
reason: error instanceof Error ? error.message : String(error),
})
failures.push(`ACS leave: ${error instanceof Error ? error.message : String(error)}`)
}
const hadScopedLostListener = Boolean(attempt.scopedLostUnsub)
attempt.scopedLostUnsub?.()
attempt.scopedLostUnsub = null
softapTrace("softap_teardown_step", {
attempt: attempt.id,
step: "scopedLostListener",
outcome: hadScopedLostListener ? "ok" : "not taken",
})
failures.push(
...(await this.settleSoftapTeardown(attempt, {
acsLeave: {ok: acsLeaveOk, durationMs: Date.now() - acsLeaveStartedAt},
defaultNetwork: {ok: defaultNetworkOk, durationMs: defaultNetworkMs},
})),
)
if (failures.length > 0) {
this.softapCleanupError = failures.join("; ")
console.warn("[LocalMiniappRuntime] softap_cleanup_failed", {attempt: attempt.id, failures})
}
// The recorded failures are what the *next* join refuses on, so they are logged as the list
// that will be quoted back to the wearer rather than only as the individual step failures.
softapTrace("softap_teardown_done", {
attempt: attempt.id,
durationMs: Date.now() - teardownStartedAt,
refusesNextCall: failures.length > 0,
failures: failures.join("; "),
endRefused: Boolean(endFailure),
})
attempt.releaseHotspot?.()
attempt.releaseHotspot = undefined
if (endFailure) throw endFailure
}
/**
* Send one hotspot command, re-sending it once if a session refresh cancelled it.
*
* The retry lives inside the unit chained onto [glassesHotspotCommand] rather than around it,
* which is what holds the invariant: one logical hotspot operation issues at most two native
* commands, and no later operation runs between them. A retry outside the queue would let an
* `on` land between the two halves of an `off` and leave the glasses in the opposite state.
*
* Re-sending is free because ASG compares against current state first and answers a same-state
* command with its current status instead of cycling the AP.
*/
private setGlassesHotspotState(enabled: boolean) {
const send = async () => {
try {
return await BluetoothSdk.setHotspotState(enabled)
} catch (error) {
const code = (error as {code?: string} | null | undefined)?.code
if (!code || !HOTSPOT_SESSION_REFRESH_CODES.has(code)) throw error
softapTrace("softap_hotspot_session_retry", {enabled, code})
await new Promise<void>((resolve) => setTimeout(resolve, HOTSPOT_SESSION_RETRY_DELAY_MS))
return await BluetoothSdk.setHotspotState(enabled)
}
}
const run = this.glassesHotspotCommand.then(send, send)
this.glassesHotspotCommand = run.then(
() => undefined,
() => undefined,
)
return run
}
/**
* The last two gates, and the point where a timeout stops being treated as consent.
*
* Four things have to be true before the next call may start: this device is out of the ACS
* call, the WHIP listener's port is released, the glasses have acknowledged their hotspot off,
* and the phone has a validated default route again. The first and last already ran; this adds
* the two that were never waited for at all, and the ones that produced the stop-then-start
* failure — the listener was still inside its 3s tombstone and the glasses AP was still up.
*
* A bound that expires is not success. It means the resource is still held by a call nobody is
* in any more, so it is taken by force and re-verified. An ingest port that is still held
* refuses the next join. A glasses hotspot that missed its off-ack does not — the next join
* wants the AP up and will raise it again.
*
* @returns failures to record; a non-empty list refuses the next join.
*/
private async settleSoftapTeardown(
attempt: SoftapAttempt,
earlier: {acsLeave: {ok: boolean; durationMs: number}; defaultNetwork: {ok: boolean; durationMs: number}},
): Promise<string[]> {
const ingestStartedAt = Date.now()
let ingestClosed = false
try {
ingestClosed = await acsMeetingService.awaitIngestClosed(SOFTAP_INGEST_CLOSE_WAIT_MS)
} catch (error) {
softapTraceFailure("softap_teardown_step", {
attempt: attempt.id,
step: "awaitIngestClosed",
outcome: "failed",
reason: error instanceof Error ? error.message : String(error),
})
}
const ingestMs = Date.now() - ingestStartedAt
const hotspotStartedAt = Date.now()
let hotspotOff = false
let hotspotReason = ""
try {
// Idempotent by design — the command asks for "disabled" rather than toggling — so sending
// it again after the transport's own stop costs nothing and is the only way to get an ack
// that is bound to a deadline we chose.
const status = await withTimeout(
this.setGlassesHotspotState(false),
SOFTAP_HOTSPOT_OFF_ACK_MS,
"hotspot_off_ack_timeout",
)
hotspotOff = status.state === "disabled"
hotspotReason = status.state
} catch (error) {
hotspotReason = error instanceof Error ? error.message : String(error)
}
const hotspotMs = Date.now() - hotspotStartedAt
softapTrace("softap_teardown_settled", {
attempt: attempt.id,
acsLeaveMs: earlier.acsLeave.durationMs,
acsLeaveOk: earlier.acsLeave.ok,
ingestClosedMs: ingestMs,
ingestClosed,
hotspotOffMs: hotspotMs,
hotspotOff,
hotspotDetail: hotspotReason,
defaultNetworkMs: earlier.defaultNetwork.durationMs,
defaultNetworkOk: earlier.defaultNetwork.ok,
})
if (ingestClosed && hotspotOff) return []
return this.forceSoftapCleanup(attempt, {ingestClosed, hotspotOff, hotspotReason})
}
/**
* Take back what the bounded waits could not confirm was released.
*
* Runs only after a gate timed out, and re-verifies rather than assuming: the whole reason the
* barrier exists is that "it has probably finished by now" is what broke restarts.
*/
private async forceSoftapCleanup(
attempt: SoftapAttempt,
gates: {ingestClosed: boolean; hotspotOff: boolean; hotspotReason: string},
): Promise<string[]> {
const failures: string[] = []
softapTraceFailure("softap_teardown_forced", {
attempt: attempt.id,
ingestClosed: gates.ingestClosed,
hotspotOff: gates.hotspotOff,
hotspotDetail: gates.hotspotReason,
})
if (!gates.ingestClosed) {
try {
await acsMeetingService.forceCloseIngest()
// Re-asked, not assumed: `forceCloseIngest` skips the tombstone, so the latch should be
// open immediately. A short bound here is enough and a failure is real.
const closed = await acsMeetingService.awaitIngestClosed(SOFTAP_FORCED_VERIFY_MS)
if (!closed) failures.push("the video receiver did not release its port")
} catch (error) {
failures.push(`forced ingest close: ${error instanceof Error ? error.message : String(error)}`)
}
}
if (!gates.hotspotOff) {
try {
const status = await withTimeout(
this.setGlassesHotspotState(false),
SOFTAP_HOTSPOT_OFF_ACK_MS,
"hotspot_off_ack_timeout",
)
if (status.state !== "disabled") {
console.warn("[LocalMiniappRuntime] glasses hotspot still reported after disable; next join will raise it", {
attempt: attempt.id,
state: status.state,
})
}
} catch (error) {
console.warn("[LocalMiniappRuntime] glasses hotspot off ack missed; next join will raise it", {
attempt: attempt.id,
reason: error instanceof Error ? error.message : String(error),
})
}
}
softapTrace("softap_teardown_forced_done", {
attempt: attempt.id,
recovered: failures.length === 0,
failures: failures.join("; "),
})
return failures
}
private async handleMeetingLeave(packageName: string, requestId?: string): Promise<void> {
this.meetingCredentialRequests.delete(packageName)
const startedAt = Date.now()
softapTrace("meeting_leave_request", {
packageName,
requestId: requestId ?? "none",
attempt: this.softapAttempt?.id ?? "none",
})
try {
// A SoftAP call owns the hotspot, the scoped network, and the cellular pin as well as the
// ACS call, and retiring the attempt releases all of them. Returning before that finishes is
// what let the next Start race this teardown.
if (this.softapAttempt) {
await this.retireSoftapAttempt()
softapTrace("meeting_leave_result", {
packageName,
requestId: requestId ?? "none",
path: "softap",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true)
return
}
await acsMeetingService.leave(packageName)
softapTrace("meeting_leave_result", {
packageName,
requestId: requestId ?? "none",
path: "acs",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
softapTraceFailure("meeting_leave_result", {
packageName,
requestId: requestId ?? "none",
reason: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS meeting leave failed",
})
}
}
/**
* End the meeting for everyone, then tear this device down.
*
* A rejection here always means "the others may still be in the meeting", never "you are still in
* it": both paths below complete local teardown before the error surfaces.
*/
private async handleMeetingEnd(packageName: string, requestId?: string): Promise<void> {
const startedAt = Date.now()
const softap = Boolean(this.softapAttempt)
softapTrace("meeting_end_request", {
packageName,
requestId: requestId ?? "none",
attempt: this.softapAttempt?.id ?? "none",
})
try {
if (this.softapAttempt) {
await this.retireSoftapAttempt({mode: "end"})
} else {
await acsMeetingService.endForEveryone(packageName)
}
softapTrace("meeting_end_result", {
packageName,
requestId: requestId ?? "none",
path: softap ? "softap" : "acs",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true)
} catch (err) {
// A rejection here always means the others may still be in the meeting, never that this
// device is — the log has to be readable that way round or it accuses the wrong side.
softapTraceFailure("meeting_end_result", {
packageName,
requestId: requestId ?? "none",
reason: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not end the meeting for everyone",
})
}
}
private async handleMeetingAdmit(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
if (typeof payload.participantId !== "string") throw new Error("A participant ID is required")
await acsMeetingService.admitParticipant(packageName, payload.participantId)
this.sendResult(packageName, requestId, true)
} catch (error) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: error instanceof Error ? error.message : "Could not admit this guest",
})
}
}
private async handleMeetingSetMuted(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const startedAt = Date.now()
try {
const state = await acsMeetingService.setMuted(packageName, Boolean(payload.muted))
softapTrace("meeting_set_muted", {
packageName,
requestId: requestId ?? "none",
requested: Boolean(payload.muted),
muted: state.muted,
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true, state)
} catch (err) {
softapTraceFailure("meeting_set_muted", {
packageName,
requestId: requestId ?? "none",
requested: Boolean(payload.muted),
reason: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS mute failed",
})
}
}
private async handleMeetingSetVideoEnabled(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
if (typeof payload.enabled !== "boolean") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "enabled must be a boolean",
})
return
}
const startedAt = Date.now()
try {
const state = await acsMeetingService.setVideoEnabled(packageName, payload.enabled)
softapTrace("meeting_set_video_enabled", {
packageName,
requestId: requestId ?? "none",
requested: payload.enabled,
videoEnabled: state.videoEnabled ?? "unknown",
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, true, state)
} catch (err) {
softapTraceFailure("meeting_set_video_enabled", {
packageName,
requestId: requestId ?? "none",
requested: payload.enabled,
reason: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS camera toggle failed",
})
}
}
private async handleMeetingUpdateVideoSource(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const videoSource = payload.videoSource as {type?: string; url?: string} | undefined
const whepUrl = videoSource?.type === "whep" ? (videoSource.url ?? "") : ""
if (!whepUrl) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "videoSource must be a WHEP URL",
})
return
}
try {
await acsMeetingService.updateVideoSource(packageName, whepUrl)
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS video source update failed",
})
}
}
private notifyPhotoPauseExpired(packageName: string, pauseId: string): void {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.MEETING_VIDEO_PUBLISHER,
pauseId,
status: "expired",
})
}
private async handleMeetingPauseVideoPublisher(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
if (payload.reason !== "photo") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "reason must be photo",
})
return
}
try {
const attempt = this.softapAttempt?.packageName === packageName ? this.softapAttempt : null
if (attempt && !attempt.transport) throw new Error("The glasses publisher is not ready")
const paused = attempt?.transport
? await attempt.transport.pauseVideoPublisher()
: await acsMeetingService.pauseCloudflarePublisher(packageName)
if (attempt?.transport) acsMeetingService.notePhotoPause(paused.pauseId)
this.sendResult(packageName, requestId, true, {pauseId: paused.pauseId})
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not pause the camera",
})
}
}
private async handleMeetingResumeVideoPublisher(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const pauseId = typeof payload.pauseId === "string" ? payload.pauseId : ""
if (!pauseId) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "pauseId is required",
})
return
}
try {
const attempt = this.softapAttempt?.packageName === packageName ? this.softapAttempt : null
if (attempt?.transport) await attempt.transport.resumeVideoPublisher(pauseId)
else await acsMeetingService.resumeCloudflarePublisher(pauseId)
acsMeetingService.clearPhotoPause(pauseId)
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not resume the camera",
})
}
}
private async handleMeetingShowCard(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
if (payload.kind !== "taking-photo") {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "kind must be taking-photo",
})
return
}
if (!acsMeetingService.meetingAcceptsPhoto(packageName)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "The meeting has already ended",
})
return
}
try {
await acsMeetingService.holdOutgoing("card")
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not show the photo card",
})
}
}
private async handleMeetingShowImage(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const imageUrl = typeof payload.imageUrl === "string" ? payload.imageUrl : ""
const durationMs = payload.durationMs
if (!imageUrl || typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs < 0) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: "imageUrl and durationMs are required",
})
return
}
if (!acsMeetingService.meetingAcceptsPhoto(packageName)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "The meeting has already ended",
})
return
}
try {
const imageBase64 = await loadOutgoingStill(imageUrl)
if (!acsMeetingService.meetingAcceptsPhoto(packageName)) {
throw new Error("The meeting has already ended")
}
await acsMeetingService.holdOutgoing("image", imageBase64)
this.sendResult(packageName, requestId, true, {shownAt: Date.now()})
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not show the photo",
})
}
}
private async handleMeetingShowLive(packageName: string, requestId?: string): Promise<void> {
if (!acsMeetingService.meetingAcceptsPhoto(packageName)) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: "The meeting has already ended",
})
return
}
try {
await acsMeetingService.holdOutgoing("live")
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not return to live video",
})
}
}
/**
* Direct link HD photo that never stops the glasses publisher: card, still, live, all host-side.
* `NOT_IMPLEMENTED` with `reason: "unsupported"` tells the miniapp to use its pause-based path.
*/
private async handleMeetingCaptureStill(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const durationMs = payload.durationMs
if (
typeof durationMs !== "number" ||
!Number.isFinite(durationMs) ||
durationMs < 0 ||
durationMs > STILL_MAX_DURATION_MS
) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INVALID_ARGUMENT,
message: `durationMs must be between 0 and ${STILL_MAX_DURATION_MS}`,
})
return
}
const attempt = this.softapAttempt?.packageName === packageName ? this.softapAttempt : null
if (!attempt?.transport || !acsMeetingService.stillCaptureSupported()) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: attempt?.transport
? "This Mentra App cannot share a Direct link photo without pausing the camera"
: "Only a Direct link call can capture a still without pausing the camera",
reason: "unsupported" satisfies MeetingStillFailure,
})
return
}
if (!attempt.transport.stillCaptureReady()) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: `The glasses camera is not live (${attempt.transport.currentPhase()})`,
reason: "not_live" satisfies MeetingStillFailure,
})
return
}
const startedAt = Date.now()
const stillId = typeof payload.stillId === "string" ? payload.stillId : ""
try {
const result = await acsMeetingService.captureStill(packageName, {
durationMs,
onProgress: (phase) => {
softapTrace("meeting_capture_still_progress", {packageName, phase, elapsedMs: Date.now() - startedAt})
if (stillId) this.sendToMiniapp(packageName, {type: MiniappResponseType.MEETING_STILL, stillId, phase})
},
})
softapTrace("meeting_capture_still", {
packageName,
requestId: result.requestId,
bytes: result.bytes,
cardMs: result.timings.cardMs,
stillMs: result.timings.stillMs,
heldMs: result.timings.heldMs,
totalMs: result.timings.totalMs,
})
this.sendResult(packageName, requestId, true, result)
} catch (err) {
const reason: MeetingStillFailure = err instanceof MeetingStillError ? err.reason : "glasses_rejected"
softapTraceFailure("meeting_capture_still", {
packageName,
reason,
message: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startedAt,
})
this.sendResult(packageName, requestId, false, undefined, {
code:
reason === "unsupported"
? MiniappErrorCode.NOT_IMPLEMENTED
: reason === "cancelled"
? MiniappErrorCode.REQUEST_ABORTED
: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Could not share the photo",
reason,
})
}
}
private async handleMeetingGetState(packageName: string, requestId?: string): Promise<void> {
// No meeting and no join in flight means nothing to adopt. Native keeps reading `connecting`
// from a retired SoftAP attempt's `prepareAgent` until its teardown reaches the ACS leave; a
// respawned Mentra Call adopted that as its own join and, with no owner to push it a terminal
// state, sat on "Starting call…" until the wearer cancelled.
if (acsMeetingService.ownerPackage() !== packageName && !this.hasLiveSoftapAttempt(packageName)) {
this.sendResult(packageName, requestId, true, {state: "idle", muted: false})
return
}
try {
const state = await acsMeetingService.readState(packageName)
this.sendResult(packageName, requestId, true, state)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "ACS getState failed",
})
}
}
/**
* Phone Wi-Fi requests use host seams and never change miniapp foreground.
*/
private async handlePhoneWifiRequest(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
try {
const result = await invokePhoneWifiSeam(getUiSeams(), payload)
this.sendResult(packageName, requestId, true, result)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string} | null)?.code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Phone Wi-Fi request failed",
})
}
}
/**
* session.glasses.requestWifiSetup — open the phone's glasses Wi-Fi setup
* flow. The host owns the actual UI via the `engine.configure({ui})` seam;
* this just forwards the request and reports success/failure.
*/
private async handleRequestWifiSetup(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const requestWifiSetup = getUiSeams().requestWifiSetup
if (!requestWifiSetup) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_IMPLEMENTED,
message: "Wi-Fi setup is not configured on this host",
})
return
}
try {
await requestWifiSetup(payload.reason as string | undefined, packageName)
this.sendResult(packageName, requestId, true)
} catch (err) {
this.sendResult(packageName, requestId, false, undefined, {
code: (err as {code?: string}).code || MiniappErrorCode.INTERNAL,
message: err instanceof Error ? err.message : "Wi-Fi setup failed",
})
}
}
/**
* Wire the PhoneStreamCoordinator's status callback so coordinator-emitted
* updates become `EVENT { streamType: "stream_status" }` envelopes on the
* subscribing miniapp(s).
*/
public wireStreamingStatusFanout(): void {
const streaming = phoneStreamCoordinator
if (!streaming) return
streaming.setStatusSubscriber((packageName, update) => {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: "stream_status",
data: {
streamId: update.streamId,
status: update.status,
source: update.source,
...(update.data || {}),
},
})
})
}
// ===========================================================================
// Public subscribe helper
// ===========================================================================
/**
* Standalone subscribe — lets external code subscribe a registered miniapp to
* streams without going through the envelope protocol.
*
* Returns `{ok: true}` on success, or `{ok: false, error}` on failure.
*/
public subscribe(packageName: string, streams: string[]): {ok: boolean; error?: string} {
const app = this.connectedApps.get(packageName)
if (!app) {
return {ok: false, error: `App ${packageName} is not registered`}
}
if (!Array.isArray(streams)) {
return {ok: false, error: "streams must be an array"}
}
console.log(`${LOG_TAG}: subscribe(${packageName}, [${streams.join(", ")}])`)
// Check microphone permission for mic-requiring streams
const micStreams = ["transcription", "translation", "audio_chunk", "vad", "wake_word"]
const needsMic = streams.some((s: string) => micStreams.some((m) => s.startsWith(m) || s === m))
if (needsMic) {
const hasMicPermission = app.installedManifest?.permissions?.some((p) => p.type === "MICROPHONE")
if (!hasMicPermission) {
return {ok: false, error: "MICROPHONE permission not declared in miniapp.json"}
}
}
// Add new subscriptions
const previousSubscriptions = app.subscriptions
app.subscriptions = new Set(streams)
app.transcriptionListeners.replace(
transcriptionRegistrations(undefined, streams, new Map()),
cloudClientService.getAudioPosition(),
)
this.replaceStreamSubscribers(packageName, previousSubscriptions, app.subscriptions)
this.recomputeMicRequirements()
this.updateCloudSubscriptions()
return {ok: true}
}
// ===========================================================================
// Mic requirements
// ===========================================================================
private getConfiguredMicGates(): {vadEnabled: boolean | null; loudnessGateEnabled: boolean | null} {
const bluetoothSettings = useSettingsStore.getState().getBluetoothSettings()
const configuredVad = bluetoothSettings.voice_activity_detection_enabled
const configuredLoudnessGate = bluetoothSettings.loudness_gate_enabled
return {
vadEnabled: typeof configuredVad === "boolean" ? configuredVad : null,
loudnessGateEnabled: typeof configuredLoudnessGate === "boolean" ? configuredLoudnessGate : null,
}
}
private recomputeMicRequirements(): void {
let anyPcm = false
let anyLc3 = false
for (const [stream, subscribers] of this.streamSubscribers) {
if (subscribers.size === 0) continue
// The wake word and voice activity run natively on phone-side PCM.
if (stream === "audio_chunk" || stream === "wake_word" || stream === "vad") anyPcm = true
if (stream.startsWith("transcription:") || stream.startsWith("translation:")) anyLc3 = true
}
wakeWordService.setSubscribed(this.hasStreamSubscribers("wake_word"), (event) =>
this.forwardEvent("wake_word", event),
)
speechActivityService.setEnabled(this.hasStreamSubscribers("vad"))
micStateCoordinator.setLocalRequirements({
pcm: anyPcm,
lc3: anyLc3,
...this.getConfiguredMicGates(),
})
}
/**
* Recompute the aggregated v2 cloud subscription list across all local miniapps.
*
* Cloud-dependent streams (transcription:*, translation:*) only flow if the
* v2 runtime knows the phone wants them. Local-only streams (button_press, etc.)
* are NOT sent — they come from the Bluetooth SDK, not from cloud.
*/
private updateCloudSubscriptions(): void {
// The on-device recognizer reports its state back synchronously from
// setDemand; that report asks for another pass instead of nesting one.
if (this.updatingCloudSubscriptions) {
this.cloudSubscriptionsDirty = true
return
}
this.updatingCloudSubscriptions = true
try {
do {
this.cloudSubscriptionsDirty = false
this.applyCloudSubscriptions()
} while (this.cloudSubscriptionsDirty)
} finally {
this.updatingCloudSubscriptions = false
}
}
private updatingCloudSubscriptions = false
private cloudSubscriptionsDirty = false
private applyCloudSubscriptions(): void {
const cloudStreams = new Set<string>()
for (const [stream, subscribers] of this.streamSubscribers) {
if (subscribers.size === 0) continue
// Only transcription / translation need cloud delivery. Location and
// notifications are sourced natively on the phone — no cloud hop.
if (stream.startsWith("translation:")) {
cloudStreams.add(stream)
}
}
// A transcription stream goes to the cloud only while a listener on it
// needs the cloud; on-device transcription runs only while one needs it.
this.refreshTranscriptionRouting()
let localDemand = false
for (const [packageName, app] of this.connectedApps) {
const state = this.transcriptionRoutingState(packageName)
for (const route of app.transcriptionListeners.routes()) {
if (needsCloud(route, route.source, route.target)) cloudStreams.add(route.stream)
if (needsLocal(route, route.source, state)) localDemand = true
}
}
// Mirror the same set as typed AudioSubscription[] and push it to the cloud
// runtime.
this.ensureCloudResultsWired()
const subs = this.buildCloudAudioSubscriptions(cloudStreams)
const nextKey = this.audioSubscriptionKey(subs)
if (this.cloudAudioSubscriptionSync.begin(nextKey)) {
console.log(
`${LOG_TAG}: updateCloudSubscriptions streams=[${Array.from(cloudStreams).join(", ")}] cloudSubs=${subs.length}`,
)
cloudClientService
.setSubscriptions(subs)
.then(() => {
this.cloudAudioSubscriptionSync.succeeded(nextKey)
})
.catch((err) => {
// Best-effort: the cloud may not be connected yet. Keep failed writes
// retryable; otherwise a reconnect that recomputes the same desired
// transcription set gets deduped and local captions never recover.
this.cloudAudioSubscriptionSync.failed(nextKey)
console.warn(`${LOG_TAG}: cloud setSubscriptions failed: ${(err as Error)?.message ?? err}`)
})
}
// On-device transcription always runs the Speech-page model; its language,
// not the subscription's, decides what local transcripts are tagged with.
localSttFallbackCoordinator.setDemand(localDemand)
this.broadcastTranscriptionModelStatus()
}
// ===========================================================================
// Transcription routing (cloud or on-device, per listener)
// ===========================================================================
/** When each transcript source last spoke, to switch listeners only where both have settled. */
private readonly utterances = new UtteranceTracker()
/** Which sources were up at the last routing pass, to notice one starting. */
private sourcesUp = {cloud: false, local: false}
/** Cloud audio position at the last on-device final. */
private localFinalWatermark: AudioPosition | null = null
/** Bumped whenever the on-device recognizer starts or stops: a drain holds only for the run it drained. */
private localGeneration = 0
/** A drain that just completed, for the routing pass it triggers only; and whether one is running. */
private localDrain: {generation: number; watermark: AudioPosition | null} | null = null
private localDrainRunning = false
/** Re-routes once a waiting switch's sources settle, since silence brings no transcript to do it. */
private handoffTimer: {id: number; at: number} | null = null
/** Cloud transcription is allowed by this deployment and connected. */
private cloudSpeechUp(): boolean {
return isFeatureEnabled("cloudSpeech") && cloudClientService.isConnected()
}
/** What one miniapp's listeners can be transcribed with right now. */
private transcriptionRoutingState(packageName: string): TranscriptionRoutingState {
return {
cloudConnected: this.cloudSpeechUp(),
onDevice: isFeatureEnabled("onDeviceSpeech"),
localLanguage: localSttFallbackCoordinator.getActiveLanguage(),
pickedLanguage: sttModelManager.getBcp47ForLanguage(),
hints: this.transcriptionHintsByApp.get(packageName) ?? [],
}
}
/**
* Moves every transcription listener toward the source it should use now
* (see TranscriptionRouting: a planned switch waits for a settled pause and
* a drain of the on-device recognizer). Returns true when any listener's
* source or target changed, which can change what must run.
*/
private refreshTranscriptionRouting(): boolean {
const cloudConnected = this.cloudSpeechUp()
const localActive = localSttFallbackCoordinator.isActive()
const now = Date.now()
// A source that stopped reports nothing more; one that started may be
// working on speech it has not reported yet.
for (const [source, up] of [
["cloud", cloudConnected],
["local", localActive],
] as const) {
if (up && !this.sourcesUp[source]) this.utterances.started(source, now)
if (!up) this.utterances.clear(source)
if (source === "local" && up !== this.sourcesUp.local) this.localGeneration++
this.sourcesUp[source] = up
}
const drained = this.localDrain !== null && this.localDrain.generation === this.localGeneration
let changed = false
let needsDrain = false
for (const [packageName, app] of this.connectedApps) {
const state = this.transcriptionRoutingState(packageName)
const routed = app.transcriptionListeners.route({
target: (listener) => targetSource(listener, state),
canDeliver: (source) => (source === "cloud" ? cloudConnected : localActive),
busy: (source, stream) => this.utterances.busy(source, stream, now),
drained,
plannedWatermark: this.localDrain?.watermark ?? null,
forcedWatermark: this.localFinalWatermark,
})
if (routed.changed) changed = true
if (routed.needsDrain) needsDrain = true
}
if (needsDrain) this.drainLocalRecognizer()
this.scheduleHandoff(now)
return changed
}
/**
* Has the on-device recognizer report everything it has heard and start
* over (finishTranscription): the boundary of a planned switch. What it
* reports goes to the listeners still on-device. The drain then serves the
* switches ready in the routing pass it triggers, and only those: the
* recognizer keeps hearing audio, so any later switch drains again. A model
* that cannot finish early reports nothing, and the quiet window is the
* boundary.
*/
private drainLocalRecognizer(): void {
if (this.localDrainRunning) return
this.localDrainRunning = true
const generation = this.localGeneration
const watermark = cloudClientService.getAudioPosition()
void this.finishLocalUtterance()
.catch((error) => console.warn(`${LOG_TAG}: draining on-device transcription failed`, error))
.then(() => {
this.localDrainRunning = false
// Everything the recognizer had is reported; its next words are new speech.
this.utterances.clear("local")
this.localDrain = {generation, watermark}
const changed = this.refreshTranscriptionRouting()
this.localDrain = null
if (changed) this.updateCloudSubscriptions()
})
}
/**
* Arms a timer for the moment the next busy source settles while any
* listener waits to switch, so the switch (and dropping what it no longer
* needs, such as a cloud stream) happens during silence too.
*/
private scheduleHandoff(now: number): void {
const waiting = [...this.connectedApps.values()].some((app) => app.transcriptionListeners.switching())
const at = waiting ? this.utterances.nextSettle(now) : null
if (this.handoffTimer && at !== null && this.handoffTimer.at <= at) return
if (this.handoffTimer) BgTimer.clearTimeout(this.handoffTimer.id)
this.handoffTimer = null
if (at === null) return
const id = BgTimer.setTimeout(() => {
if (this.handoffTimer?.id !== id) return
this.handoffTimer = null
if (this.refreshTranscriptionRouting()) this.updateCloudSubscriptions()
}, at - now)
this.handoffTimer = {id, at}
}
/**
* Build the cloud `AudioSubscription[]` from the miniapp cloud-stream key set.
*
* Stream keys: `transcription:<lang>` (lang may be `auto`, `en-US`, …) and
* `translation:<source>:<target>` (3 colon-parts; source/target may be `*`
* or `auto` wildcards, target may also be `*`). The cloud protocol requires a
* concrete `target: string` for translation, so wildcard-target translation
* keys (`translation:<source>:*`, `translation:*:*`, `translation:auto`) have
* no cloud equivalent and are skipped. Wildcard/`auto` SOURCE maps to
* `{mode: "auto"}`.
*/
private buildCloudAudioSubscriptions(cloudStreams: Set<string>): AudioSubscription[] {
const subs: AudioSubscription[] = []
// Union of every connected app's TRANSCRIPTION_CONFIG hints. Hints only
// apply to the auto-mode TRANSCRIPTION subscription (the wire schema has
// no hints field on specific-language sources — the language IS the hint
// there), and are deliberately NOT attached to translation sources.
const hintUnion = [...new Set([...this.transcriptionHintsByApp.values()].flat())].sort()
const langSource = (code: string): LanguageSource =>
code === "auto" || code === "*" ? {mode: "auto"} : {mode: "specific", code}
for (const stream of cloudStreams) {
if (stream.startsWith("transcription:")) {
const lang = stream.substring("transcription:".length)
const source = langSource(lang)
subs.push({
kind: "transcription",
language: source.mode === "auto" && hintUnion.length > 0 ? {mode: "auto", hints: hintUnion} : source,
})
} else if (stream.startsWith("translation:")) {
const parts = stream.split(":")
// Only `translation:<source>:<target>` maps cleanly; a concrete target
// is required by the cloud schema.
if (parts.length === 3) {
const [, source, target] = parts
if (target === "*") continue
subs.push({kind: "translation", source: langSource(source), target})
}
}
}
return subs
}
private audioSubscriptionKey(subs: AudioSubscription[]): string {
return JSON.stringify(
subs
.map((sub) => {
if (sub.kind === "transcription") {
return {
kind: sub.kind,
language: sub.language,
}
}
return {
kind: sub.kind,
source: sub.source,
target: sub.target,
}
})
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
)
}
/**
* Wire the cloud's transcription/translation results into the existing
* miniapp fan-out exactly once. Maps each cloud result back to the
* cloud-to-app data shape `forwardEvent` already forwards, keyed on the
* `transcription:<lang>` / `translation:<source>:<target>` stream strings, so
* subscribed miniapps receive identical envelopes.
*/
private ensureCloudResultsWired(): void {
if (this.cloudResultsWired) return
this.cloudResultsWired = true
cloudClientService.onTranscript((d: TranscriptionData) => {
const receivedAt = Date.now()
if (TRANSCRIPT_TIMING_TELEMETRY) {
console.log(
`${LOG_TAG}: transcript cloud_recv t=${receivedAt} final=${d.isFinal} lang=${
d.resolvedLanguage
} text="${d.text.slice(0, 48)}"`,
)
}
this.forwardEvent(
`transcription:${d.resolvedLanguage}`,
{
type: "transcription",
text: d.text,
isFinal: d.isFinal,
utteranceId: d.utteranceId,
transcribeLanguage: d.resolvedLanguage,
detectedLanguage: d.languageDetected ? d.resolvedLanguage : undefined,
startTime: d.startMs,
endTime: d.endMs,
speakerId: d.speakerId,
duration: d.durationMs,
provider: d.provider,
confidence: d.confidence,
__hostReceivedAt: receivedAt,
},
"cloud",
d.provider === "soniox" && (d.frameTimelineVersion === 1 || d.tokens.some((token) => token.audioPosition))
? d.tokens
: undefined,
)
})
cloudClientService.onTranslation((d: TranslationData) => {
this.forwardEvent(`translation:${d.source.language}:${d.target.language}`, {
type: "translation",
text: d.text,
originalText: d.originalText,
isFinal: d.isFinal,
utteranceId: d.utteranceId,
startTime: d.startMs,
endTime: d.endMs,
speakerId: d.speakerId,
duration: d.durationMs,
transcribeLanguage: d.source.language,
translateLanguage: d.target.language,
didTranslate: true,
provider: d.provider,
confidence: d.confidence,
})
})
}
private ensureCloudStatusWired(): void {
if (this.cloudStatusWired) return
this.cloudStatusWired = true
cloudClientService.onStatusChanged((status) => {
if (status.status === "connected") {
for (const app of this.connectedApps.values()) {
app.transcriptionListeners?.observe(cloudClientService.getAudioPosition())
}
// A miniapp that connected before the cloud client was ready never got
// its auth token; now that we're connected, mint it without waiting for
// the retry backoff (or a full manual reconnect).
this.redriveMiniappAuthDelivery()
}
// A disconnect can hand cloud Captions back to the shared native model.
// Recompute ownership on both disconnect and reconnect.
this.updateCloudSubscriptions()
this.broadcastCloudStatus()
})
sttModelManager.onSelectionChanged(() => this.updateCloudSubscriptions())
// On-device transcription starting or stopping moves preferLocal and fallback listeners.
localSttFallbackCoordinator.onModelStatusChanged(() => this.updateCloudSubscriptions())
useSettingsStore.subscribe(
(s) => s.getSetting(ISLAND_SETTINGS_KEYS.localSttFallbackActive),
() => {
this.broadcastCloudStatus()
},
)
}
// ===========================================================================
// On-device transcription model status (session.transcription.onModelStatus)
// ===========================================================================
/**
* The on-device model state as one miniapp sees it. Its on-device listeners
* are the localOnly and preferLocal ones, and every listener while the cloud
* is down. The phone runs one model, the one picked on the Speech page, so a
* miniapp whose on-device listeners all ask for another language is told
* it's unavailable.
*/
private transcriptionModelStatusFor(packageName: string): {
language: string
state: "downloading" | "loading" | "ready" | "unavailable"
progress?: number
reason?: string
} {
const status = localSttFallbackCoordinator.getModelStatus()
const language = status.language || sttModelManager.getBcp47ForLanguage()
if (!isFeatureEnabled("onDeviceSpeech")) {
return {language, state: "unavailable", reason: "On-device speech is disabled by this deployment"}
}
const cloudConnected = this.cloudSpeechUp()
const onDeviceListeners = (this.connectedApps.get(packageName)?.transcriptionListeners.routes() ?? []).filter(
(listener) => listener.processing !== "preferCloud" || !cloudConnected,
)
if (onDeviceListeners.length === 0) {
return {language, state: "unavailable", reason: "No on-device transcription subscription"}
}
// "auto" follows the picked model; any other language must be the picked one.
const hints = this.transcriptionHintsByApp.get(packageName) ?? []
if (!onDeviceListeners.some((listener) => onDeviceServes(listener, language, hints))) {
return {
language,
state: "unavailable",
reason: `The on-device speech model is ${language}; choose another language on the Speech page`,
}
}
switch (status.state) {
case "downloading":
return {language, state: "downloading", progress: status.progress ?? 0}
case "ready":
return {language, state: "ready"}
case "unavailable":
return {language, state: "unavailable", reason: status.reason ?? "The on-device speech model is unavailable"}
default:
// "idle" only lasts until the coordinator picks up this subscription.
return {language, state: "loading"}
}
}
private sendTranscriptionModelStatus(packageName: string, force = false): void {
const app = this.connectedApps.get(packageName)
if (!app) return
const data = this.transcriptionModelStatusFor(packageName)
const key = JSON.stringify(data)
if (!force && app.lastTranscriptionModelStatus === key) return
app.lastTranscriptionModelStatus = key
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: MiniappStreamType.TRANSCRIPTION_MODEL_STATUS,
data,
})
}
private broadcastTranscriptionModelStatus(): void {
for (const packageName of this.streamSubscribers.get(MiniappStreamType.TRANSCRIPTION_MODEL_STATUS) ?? []) {
this.sendTranscriptionModelStatus(packageName)
}
}
/** Bumped after each final local transcript reaches miniapps; finishUtterance waits on it. */
private localFinalSeq = 0
private readonly localFinalWaiters = new Set<() => void>()
/**
* End the current on-device utterance. Resolves with its final text only
* after that final transcript has gone out to miniapps, "" when nothing was
* pending, or null when no streaming model is active or it can't finish early.
*/
private async finishLocalUtterance(): Promise<string | null> {
if (!["android", "ios"].includes(Platform.OS) || typeof BluetoothSdk.finishTranscription !== "function") return null
if (!localSttFallbackCoordinator.isActive()) return null
const before = this.localFinalSeq
const result: unknown = await BluetoothSdk.finishTranscription()
if (typeof result !== "string") return null
if (result && this.localFinalSeq === before) {
// Native emits the final event before resolving, but the event and the
// promise reach JavaScript separately; wait briefly for the event.
await new Promise<void>((resolve) => {
const done = () => {
BgTimer.clearTimeout(timer)
this.localFinalWaiters.delete(done)
resolve()
}
const timer = BgTimer.setTimeout(done, LocalMiniappRuntime.FINISH_DELIVERY_WAIT_MS)
this.localFinalWaiters.add(done)
})
}
return result
}
private static readonly FINISH_DELIVERY_WAIT_MS = 1000
private noteLocalFinalDelivered(): void {
this.localFinalSeq++
for (const waiter of [...this.localFinalWaiters]) waiter()
}
private currentCloudStatus(): CloudClientStatusSnapshot {
const base = cloudClientService.getStatus()
const fallbackActive =
(useSettingsStore.getState().getSetting(ISLAND_SETTINGS_KEYS.localSttFallbackActive) as boolean | undefined) ===
true
return {
status: base.status,
audioTransport: fallbackActive ? "offline" : base.audioTransport,
}
}
private broadcastCloudStatus(): void {
const status = this.currentCloudStatus()
for (const packageName of this.connectedApps.keys()) {
this.sendCloudStatusToMiniapp(packageName, status)
}
}
private sendCloudStatusToMiniapp(packageName: string, status = this.currentCloudStatus()): void {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: CLOUD_STATUS_STREAM,
data: status,
})
}
// ===========================================================================
// Stream fan-out
// ===========================================================================
/** Whether any miniapp subscribes to `stream`. */
public hasStreamSubscribers(stream: string): boolean {
return (this.streamSubscribers.get(stream)?.size ?? 0) > 0
}
/**
* Forward a streamed event to all miniapps subscribed to the given stream.
*
* Event name translation:
* - Incoming "head_up" → miniapp protocol uses "head_position" (HEAD_POSITION)
* - Incoming "VAD" (uppercase) → miniapp protocol uses "vad" (lowercase)
*/
public forwardEvent(
streamType: string,
data: unknown,
transcriptionSource?: TranscriptionEventSource,
tokens?: TranscriptionData["tokens"],
): void {
// Normalize incoming event names to miniapp protocol stream types
const normalizedStream = this.normalizeStreamType(streamType)
// Collect all subscribers: exact match, plus wildcard matches for streams
// that carry a language tag. A miniapp subscribed to "transcription:auto"
// should receive any "transcription:<lang>" event (the detected language
// is conveyed in the event data, not the stream key).
//
// Translation streams support cloud v3's wildcard patterns. Incoming
// events are keyed `translation:<source>:<target>` and we match against
// any of:
// translation:*:* — all-pairs (TranslationModule.on)
// translation:*:<target> — any-source → target (TranslationModule.to)
// translation:<source>:* — source → any-target (rare)
// translation:<source>:<target> — exact (TranslationModule.fromTo)
// translation:auto — back-compat alias for *:*
const matchedSubs = new Set<string>()
const exact = this.streamSubscribers.get(normalizedStream)
if (exact) for (const p of exact) matchedSubs.add(p)
if (normalizedStream.startsWith("transcription:")) {
const autoSubs = this.streamSubscribers.get("transcription:auto")
if (autoSubs) for (const p of autoSubs) matchedSubs.add(p)
} else if (normalizedStream.startsWith("translation:")) {
// translation:<source>:<target> — match each wildcard variant.
const parts = normalizedStream.split(":")
// parts[0] = "translation", parts[1] = source, parts[2] = target
if (parts.length === 3) {
const [, source, target] = parts
const patterns = [
"translation:auto", // legacy alias for *:*
"translation:*:*", // cloud v3 "all pairs"
`translation:*:${target}`, // cloud v3 "to <target>"
`translation:${source}:*`, // cloud v3 "from <source>"
]
for (const pat of patterns) {
const subs = this.streamSubscribers.get(pat)
if (subs) for (const p of subs) matchedSubs.add(p)
}
} else {
// Malformed stream key — still honor the legacy auto alias.
const autoSubs = this.streamSubscribers.get("translation:auto")
if (autoSubs) for (const p of autoSubs) matchedSubs.add(p)
}
}
if (normalizedStream.startsWith("transcription:") && transcriptionSource) {
this.forwardTranscription(normalizedStream, data, transcriptionSource, tokens, matchedSubs)
return
}
// Touch event per-gesture fan-out. SDK-side dispatch is keyed on the
// exact streamType, so per-gesture subscribers (`touch_event:single_tap`,
// etc.) need their own EVENT envelope with the gesture-tagged streamType.
// The bare `touch_event` stream above still catches `onTouch(handler)`.
let perGestureStream: string | null = null
let outboundData = data
if (normalizedStream === MiniappStreamType.GLASSES_CONNECTION) {
const connection = toMiniappConnectionData(data)
if (!connection) return
outboundData = connection
}
if (normalizedStream === MiniappStreamType.TOUCH_EVENT) {
// The Bluetooth SDK delivers the gesture under `gestureName` (single_tap /
// double_tap / triple_tap / long_press / swipe_up / swipe_down). Surface it
// to miniapps as `TouchData.kind` and tag a per-gesture stream so
// onTouch("single_tap", ...) routes correctly.
const touch = data as {gestureName?: string; kind?: string} | null
const gesture = touch?.gestureName ?? touch?.kind
if (typeof gesture === "string" && gesture.length > 0) {
outboundData = {...(touch as object), kind: gesture}
perGestureStream = `${MiniappStreamType.TOUCH_EVENT}:${gesture}`
}
}
if (matchedSubs.size === 0 && !perGestureStream) return
for (const packageName of matchedSubs) {
// While a nav trip is active the Nav SDK's road-snapped fixes are
// already being forwarded via addLocationListener (see NAV_START handler).
// Suppress the raw background-GPS forward for that miniapp so the two
// streams don't interleave and cause the position to jump back to the
// real-phone location during simulation.
if (normalizedStream === MiniappStreamType.LOCATION_UPDATE && this.navigationHandlers.isTripActive(packageName)) {
continue
}
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: normalizedStream,
data: outboundData,
})
}
// Send a separate envelope to per-gesture subscribers tagged with the
// gesture-specific streamType so SDK-side dispatch routes correctly.
if (perGestureStream) {
const gestureSubs = this.streamSubscribers.get(perGestureStream)
if (gestureSubs) {
for (const packageName of gestureSubs) {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: perGestureStream,
data: outboundData,
})
}
}
}
}
/**
* Sends one transcript to each listener that hears its stream and currently
* gets its text from its source, tagged with that source. Then records where
* the source is in its utterance: a final can complete a listener's switch
* that waited for it.
*/
private forwardTranscription(
stream: string,
data: unknown,
source: TranscriptionEventSource,
tokens: TranscriptionData["tokens"] | undefined,
packageNames: Set<string>,
): void {
const transcript = (data ?? {}) as {text?: string; isFinal?: boolean; __hostReceivedAt?: number}
const isFinal = transcript.isFinal === true
// A switch that waited only on an utterance that went stale happens before this transcript.
let moved = this.refreshTranscriptionRouting()
const audioPosition = cloudClientService.getAudioPosition()
for (const packageName of packageNames) {
const app = this.connectedApps.get(packageName)
if (!app) continue
const deliveries = app.transcriptionListeners.deliveries(
stream,
source,
transcript.text ?? "",
tokens,
audioPosition,
)
if (TRANSCRIPT_TIMING_TELEMETRY && deliveries.length > 0) {
const now = Date.now()
console.log(
`${LOG_TAG}: transcript fanout t=${now} app=${packageName} source=${source} final=${isFinal} hostDelta=${
transcript.__hostReceivedAt ? now - transcript.__hostReceivedAt : -1
}ms text="${(transcript.text ?? "").slice(0, 48)}"`,
)
}
for (const delivery of deliveries) {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.EVENT,
streamType: stream,
data: {...transcript, text: delivery.text, source},
transcriptionRoute: delivery.route,
...(delivery.listenerId ? {listenerId: delivery.listenerId} : {}),
})
}
}
if (source === "local" && isFinal) {
this.localFinalWatermark = audioPosition ?? this.localFinalWatermark
this.noteLocalFinalDelivered()
}
this.utterances.note(source, stream, isFinal, Date.now())
if (this.refreshTranscriptionRouting()) moved = true
if (moved) this.updateCloudSubscriptions()
}
/**
* Normalize incoming event names to miniapp stream type values.
*/
private normalizeStreamType(cloudEventName: string): string {
// Incoming event names → miniapp protocol translations.
// Bluetooth SDK event names don't always match the miniapp wire values.
switch (cloudEventName) {
case "head_up":
return MiniappStreamType.HEAD_POSITION // head_up → head_position
case "accel_event":
return MiniappStreamType.ACCEL_DATA // accel_event (native) → accel_data
case "VAD":
return MiniappStreamType.VAD // VAD (uppercase) → vad (lowercase)
case "glasses_battery_update":
return MiniappStreamType.GLASSES_BATTERY // glasses_battery_update → glasses_battery
case "glasses_connection_state":
return MiniappStreamType.GLASSES_CONNECTION // glasses_connection_state → glasses_connection
default:
// Preserve case for typed streams like "transcription:en-US" / "translation:en-US:fr-FR"
// whose language tags are case-sensitive (BCP-47). Lowercase only plain names.
if (cloudEventName.includes(":")) return cloudEventName
return cloudEventName.toLowerCase()
}
}
// ===========================================================================
// Outbound helpers
// ===========================================================================
/**
* Send a payload to a connected miniapp, wrapped in an envelope.
*/
/**
* Push a speaker-state transition to the owning miniapp. Idempotent: if
* the new state matches the cached one (and isn't an error), no envelope
* is sent. Error events are always sent — they're transient and the SDK
* settles back to a non-error state immediately after.
*/
private setSpeakerState(
packageName: string,
next: SpeakerStateValue,
extra?: {errorCode?: string; errorMessage?: string; durationMs?: number},
): void {
const app = this.connectedApps.get(packageName)
if (!app) return
if (app.speakerState === next && next !== "error") return
app.speakerState = next === "error" ? "error" : next
this.sendToMiniapp(packageName, {
type: MiniappResponseType.SPEAKER_STATE,
state: next,
...(extra?.errorCode !== undefined ? {errorCode: extra.errorCode} : {}),
...(extra?.errorMessage !== undefined ? {errorMessage: extra.errorMessage} : {}),
...(extra?.durationMs !== undefined ? {durationMs: extra.durationMs} : {}),
})
// After an error event, immediately transition to "stopped" so the
// SDK's isPlaying getter reads false and a new play()/speak() call
// starts cleanly from idle/stopped.
if (next === "error") {
app.speakerState = "stopped"
this.sendToMiniapp(packageName, {
type: MiniappResponseType.SPEAKER_STATE,
state: "stopped",
})
}
}
private sendToMiniapp(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
const app = this.connectedApps.get(packageName)
if (!app) {
console.warn(`${LOG_TAG}: sendToMiniapp — ${packageName} not connected`)
return
}
const envelope: MiniappEnvelope = {
payload,
requestId,
}
const serialized = serializeEnvelope(envelope)
if ((payload as Record<string, unknown>)?.streamType?.toString().startsWith("transcription")) {
// console.log(
// `${LOG_TAG}: sendToMiniapp → ${packageName} streamType=${(payload as Record<string, unknown>).streamType}`,
// )
}
try {
app.sendMessage(serialized)
} catch (err) {
console.error(`${LOG_TAG}: sendToMiniapp error for ${packageName}:`, err)
}
}
/**
* Send a REQUEST_RESULT response.
*/
// ===========================================================================
// Inter-miniapp interop (session.miniapps + session.actions.invoke)
// ===========================================================================
/** Max serialized size of an action call's params / result (256 KB). */
private static readonly ACTION_PAYLOAD_CAP = 256 * 1024
/** Outstanding action invocations, keyed by host-generated callId. */
private actionCalls = new Map<
string,
{
targetPackageName: string
timer: number
resolve: (value: unknown) => void
reject: (error: Error & {code?: string}) => void
releaseWake?: () => Promise<void>
}
>()
private actionCallSeq = 0
/** Bumped by cleanup(): an install requested before sign-out or a deployment switch never activates. */
private installSessionEpoch = 0
/** Changes at cleanup: an install started earlier belongs to the ended session. */
public installSession(): number {
return this.installSessionEpoch
}
private interopApps(): ClientApp[] {
return useAppStatusStore.getState().apps
}
private isSystemPackage(packageName: string): boolean {
// A local or development build never gets system privileges, whatever name it claims.
if (isLocalBuildContext(packageName) || !SYSTEM_MINIAPP_PACKAGE_SET.has(packageName)) return false
const app = this.interopApps().find((candidate) => candidate.packageName === packageName)
if (app?.offline) return true
if (!app?.local || !app.version) return false
// The bundled release, or a compatible update of it from a Mentra host.
const identity = appRegistry.getReleaseIdentity(packageName, app.version)
return identity?.source === "bundled_asset" || isHostTrustedSystemMiniapp(packageName, identity)
}
private async startInteropApp(packageName: string): Promise<boolean> {
const app = this.interopApps().find((a) => a.packageName === packageName)
if (!app) return false
// An update in progress refuses every launch path, not only Home taps.
if (useAppStatusStore.getState().updatingPackages.has(packageName)) return false
if (app.local) {
await miniappLauncher.ensureConnected(packageName)
return true
}
return useAppStatusStore.getState().start(app, {skipNavigation: true})
}
private stopInteropApp(packageName: string): Promise<void> {
return useAppStatusStore.getState().stop(packageName)
}
/** Emit an interop audit event (best-effort — never let telemetry break a call). */
private auditInterop(event: InteropAuditEvent): void {
try {
getAnalytics()?.("miniapp_interop", {
caller: event.caller,
op: event.op,
target: event.target ?? "",
actionId: event.actionId ?? "",
ok: event.ok,
errorCode: event.errorCode ?? "",
})
} catch {
/* telemetry must never break an interop call */
}
}
/** Reject the request with NOT_PERMITTED unless the caller is a system app. */
private requireSystemCaller(
packageName: string,
requestId: string | undefined,
op: InteropAuditEvent["op"],
target?: string,
): boolean {
if (this.isSystemPackage(packageName)) return true
this.auditInterop({caller: packageName, op, target, ok: false, errorCode: MiniappErrorCode.NOT_PERMITTED})
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_PERMITTED,
message: "Inter-miniapp APIs are restricted to system apps",
})
return false
}
/** Project a host ClientApp into the SDK's MiniappInfo shape (JSON over the wire). */
private buildMiniappInfo(app: ClientApp): Record<string, unknown> {
const compatibility = app.compatibility ?? {
isCompatible: true,
missingRequired: [],
missingOptional: [],
warnings: [],
}
return {
packageName: app.packageName,
name: app.name,
version: app.version ?? "",
running: app.running,
compatibility,
system: isSystemMiniappPackage(app.packageName),
actions: projectSystemActions(app.actions ?? []),
}
}
private handleMiniappsList(packageName: string, payload: Record<string, unknown>, requestId?: string): void {
if (!this.requireSystemCaller(packageName, requestId, "list")) return
const includeIncompatible = payload.includeIncompatible === true
const infos = this.interopApps()
.filter(
(a) =>
a.packageName &&
a.packageName !== packageName &&
!a.packageName.includes("@empty") &&
(includeIncompatible || a.compatibility?.isCompatible !== false),
)
.map((a) => this.buildMiniappInfo(a))
this.sendResult(packageName, requestId, true, infos)
this.auditInterop({caller: packageName, op: "list", ok: true})
}
private async handleMiniappsStart(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const target = payload.packageName as string | undefined
if (!this.requireSystemCaller(packageName, requestId, "start", target)) return
const app = target ? this.interopApps().find((a) => a.packageName === target) : undefined
if (!target || !app) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.APP_NOT_FOUND,
message: `Miniapp not found: ${target ?? "(missing packageName)"}`,
})
this.auditInterop({
caller: packageName,
op: "start",
target,
ok: false,
errorCode: MiniappErrorCode.APP_NOT_FOUND,
})
return
}
// Pre-flight the hardware gate so the caller gets a precise reason rather
// than a generic rejection (start()'s own gate would refuse it silently).
if (app.compatibility && app.compatibility.isCompatible === false) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.APP_NOT_COMPATIBLE,
message: `${target} is not compatible with the connected glasses`,
})
islandNotifications.emit({
kind: "version_incompatible",
packageName: target,
reason: `${target} is not compatible with the connected glasses`,
metadata: {missingRequired: app.compatibility.missingRequired ?? [], via: "miniapps.start"},
timestamp: Date.now(),
})
this.auditInterop({
caller: packageName,
op: "start",
target,
ok: false,
errorCode: MiniappErrorCode.APP_NOT_COMPATIBLE,
})
return
}
try {
// startInteropApp resolves to false when the app-store gate rejected the
// launch or the background context failed to spawn — don't report success.
const started = await this.startInteropApp(target)
if (started) {
// `session.miniapps.open` also brings the phone UI forward.
if (payload.foreground === true && app.local) await useAppStatusStore.getState().setForeground(target)
this.sendResult(packageName, requestId, true)
this.auditInterop({caller: packageName, op: "start", target, ok: true})
} else {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: `start of ${target} was rejected by the host (gated, updating, or failed to spawn)`,
})
this.auditInterop({
caller: packageName,
op: "start",
target,
ok: false,
errorCode: MiniappErrorCode.INTERNAL,
})
}
} catch (e) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: (e as Error)?.message ?? "start failed",
})
this.auditInterop({
caller: packageName,
op: "start",
target,
ok: false,
errorCode: MiniappErrorCode.INTERNAL,
})
}
}
private async handleMiniappsStop(
packageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const target = payload.packageName as string | undefined
if (!this.requireSystemCaller(packageName, requestId, "stop", target)) return
if (!target) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.APP_NOT_FOUND,
message: "stop requires a packageName",
})
return
}
try {
await this.stopInteropApp(target)
this.sendResult(packageName, requestId, true)
this.auditInterop({caller: packageName, op: "stop", target, ok: true})
} catch (e) {
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.INTERNAL,
message: (e as Error)?.message ?? "stop failed",
})
}
}
// ---------------------------------------------------------------------------
// Installing miniapps (system-list miniapps only)
// ---------------------------------------------------------------------------
/**
* Installing and uninstalling miniapps: only a miniapp on the system list, running the release the host installed
* for it. Both the live context's provenance and the installed release count: a development build, or another
* context that only reuses a system package's name, may not, and neither may any other miniapp.
*/
private requireSystemListCaller(
packageName: string,
requestId: string | undefined,
op: InteropAuditEvent["op"],
target?: string,
): boolean {
if (
SYSTEM_MINIAPP_PACKAGE_SET.has(packageName) &&
this.connectedApps.get(packageName)?.hostTrustedSystem === true &&
this.isSystemPackage(packageName)
) {
return true
}
this.sendResult(packageName, requestId, false, undefined, {
code: MiniappErrorCode.NOT_PERMITTED,
message: "Installing miniapps is restricted to the Mentra App's system miniapps",
})
this.auditInterop({caller: packageName, op, target, ok: false, errorCode: MiniappErrorCode.NOT_PERMITTED})
return false
}
/** The host's compatibility policy for installs and updates, or null until configured. */
public currentInstallCompatibilityPolicy(): MiniappCompatibilityPolicy | null {
const {hostVersion, supportedMiniappSdkRange} = getConfigValues()
if (!hostVersion || !supportedMiniappSdkRange) return null
const defaultWearable = useSettingsStore.getState().getSetting(ISLAND_SETTINGS_KEYS.defaultWearable) as
| DeviceTypes
| undefined
return {
hostVersion,
supportedSdkRange: supportedMiniappSdkRange,
hardwareCapabilities: getModelCapabilities(defaultWearable || DeviceTypes.NONE),
}
}
private evaluateInstallCompatibility(payload: Record<string, unknown>): MiniappInstallCompatibility {
const policy = this.currentInstallCompatibilityPolicy()
if (!policy) {
return {compatible: false, blocker: "host", reason: "Host miniapp compatibility policy is not configured"}
}
return checkMiniappInstallCompatibility(
{
minHostVersion: typeof payload.minHostVersion === "string" ? payload.minHostVersion.trim() : undefined,
sdkVersion: typeof payload.sdkVersion === "string" ? payload.sdkVersion.trim() : undefined,
hardwareRequirements: payload.hardwareRequirements,
},
policy,
)
}
/** A QR-selected build or snapshot is the user's choice; automatic updates leave it alone. */
public hasDevelopmentSelection(packageName: string): boolean {
return (
this.interopApps().some((app) => app.packageName === packageName && app.isMiniappDev) ||
getDevAppRecords().some((record) => record.packageName === packageName) ||
appRegistry.getSelectedDevSnapshot(packageName) !== null
)
}
/**
* Install the miniapp at a miniapp URL through `installMiniapp`, headlessly: the system miniapp asks the person
* first, in its own conversation. It registers the URL like every install.
*/
private async handleMiniappsInstall(
callerPackageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
if (!this.requireSystemListCaller(callerPackageName, requestId, "install")) return
const fail = (code: MiniappErrorCode, message: string, reason?: InstallMiniappErrorCode) => {
this.sendResult(callerPackageName, requestId, false, undefined, {code, message, ...(reason ? {reason} : {})})
this.auditInterop({caller: callerPackageName, op: "install", ok: false, errorCode: code})
}
const url = typeof payload.url === "string" ? payload.url.trim() : ""
if (!url) {
fail(MiniappErrorCode.INVALID_ARGUMENT, "install requires the miniapp's url")
return
}
// The package the caller agreed to; the URL must serve exactly that one.
const expected = payload.packageName === undefined ? undefined : payload.packageName
if (expected !== undefined && (typeof expected !== "string" || !expected.trim())) {
fail(MiniappErrorCode.INVALID_ARGUMENT, "install's packageName must be a package name")
return
}
try {
const {status, packageName, version} = await installMiniapp(url, {
source: "system",
...(expected !== undefined ? {expectedPackageName: expected.trim()} : {}),
})
this.sendResult(callerPackageName, requestId, true, {status, packageName, version})
this.auditInterop({caller: callerPackageName, op: "install", target: packageName, ok: true})
} catch (error) {
if (error instanceof InstallMiniappError) fail(MiniappErrorCode.INSTALL_FAILED, error.message, error.code)
else fail(MiniappErrorCode.INSTALL_FAILED, (error as Error)?.message ?? "miniapp installation failed")
}
}
private handleMiniappsInstallCheck(
callerPackageName: string,
payload: Record<string, unknown>,
requestId?: string,
): void {
if (!this.requireSystemListCaller(callerPackageName, requestId, "install")) return
this.sendResult(callerPackageName, requestId, true, this.evaluateInstallCompatibility(payload))
}
/**
* Why a system miniapp may not uninstall `target`, or null. It may uninstall a miniapp installed from a miniapp URL,
* by the person or a system miniapp. A miniapp this build bundles, one a workspace manages (its deployment manifest
* or a Fleet assignment), a release QR's and a development build stay: they belong to the build, the workspace or
* the person.
*/
private uninstallRefusal(target: string): {code: MiniappErrorCode; message: string} | null {
if (isSystemMiniappPackage(target)) {
return {code: MiniappErrorCode.NOT_PERMITTED, message: `${target} is bundled with the Mentra App`}
}
const version = appRegistry.getActiveReleaseVersion(target)
if (!version) return {code: MiniappErrorCode.APP_NOT_FOUND, message: `${target} is not installed`}
const identity = appRegistry.getReleaseIdentity(target, version)
const fromUrlOnly = appRegistry.getInstallReasons(target).every((reason) => reason === "explicit")
if (identity?.source !== "url" || !fromUrlOnly || this.hasDevelopmentSelection(target)) {
return {code: MiniappErrorCode.NOT_PERMITTED, message: `${target} wasn't installed from a miniapp URL`}
}
return null
}
private async handleMiniappsUninstall(
callerPackageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const target = typeof payload.packageName === "string" ? payload.packageName : undefined
if (!this.requireSystemListCaller(callerPackageName, requestId, "uninstall", target)) return
const fail = (code: MiniappErrorCode, message: string) => {
this.sendResult(callerPackageName, requestId, false, undefined, {code, message})
this.auditInterop({caller: callerPackageName, op: "uninstall", target, ok: false, errorCode: code})
}
if (!target) {
fail(MiniappErrorCode.INVALID_ARGUMENT, "uninstall requires a packageName")
return
}
const refused = this.uninstallRefusal(target)
if (refused) {
fail(refused.code, refused.message)
return
}
const session = this.installSessionEpoch
const late: {refusal?: {code: MiniappErrorCode; message: string}} = {}
try {
const app = this.interopApps().find((candidate) => candidate.packageName === target)
if (app?.running) await this.stopInteropApp(target)
// Checked again inside the serialized uninstall: a Fleet assignment, a workspace release or a development build
// may have arrived while the miniapp stopped, and nothing is removed once the engine session has ended.
const result = await useAppStatusStore.getState().uninstall(target, undefined, {
beforeRemove: () => {
late.refusal =
session === this.installSessionEpoch
? (this.uninstallRefusal(target) ?? undefined)
: {code: MiniappErrorCode.INTERNAL, message: `The uninstall of ${target} was cancelled`}
if (late.refusal) throw new Error(late.refusal.message)
},
})
if (result.is_error()) throw result.error
this.sendResult(callerPackageName, requestId, true)
this.auditInterop({caller: callerPackageName, op: "uninstall", target, ok: true})
} catch (error) {
if (late.refusal) fail(late.refusal.code, late.refusal.message)
else fail(MiniappErrorCode.INTERNAL, (error as Error)?.message ?? "miniapp uninstall failed")
}
}
// ---------------------------------------------------------------------------
// Declared actions
// ---------------------------------------------------------------------------
/** True iff `value` serializes larger than the action payload cap. */
private actionPayloadTooLarge(value: unknown): boolean {
try {
return JSON.stringify(value ?? null).length > LocalMiniappRuntime.ACTION_PAYLOAD_CAP
} catch {
// Unserializable — let it through; the transport's own serialize handles it.
return false
}
}
private actionError(
code: string,
message: string,
details?: Record<string, unknown>,
): Error & {code: string; details?: Record<string, unknown>} {
return Object.assign(new Error(message), {code, ...(details ? {details} : {})})
}
/**
* The action broker shared by `session.actions.invoke` and host scheduling.
* A transient action runs in an invisible, invocation-scoped wake; a
* persistent one starts the target as normal user activity. Host-audience
* actions, and every action of a background-only miniapp, are reachable only
* from the host.
*/
private async invokeDeclaredAction(
callerPackageName: string,
target: string,
actionId: string,
params: Record<string, unknown>,
timeoutMs: number,
allowHostAudience: boolean,
): Promise<unknown> {
if (this.actionPayloadTooLarge(params)) {
throw this.actionError(MiniappErrorCode.PAYLOAD_TOO_LARGE, "action params exceeded the 256 KB cap")
}
// Background-only packages stay out of every user/miniapp-facing list. The
// host resolves their installed declarations without exposing them.
const backgroundOnly = !isMiniappAvailable(target)
const app =
backgroundOnly && allowHostAudience
? (await appRegistry.getInstalledMiniapps({includeBackgroundOnly: true})).find(
(candidate) => candidate.packageName === target,
)
: this.interopApps().find((candidate) => candidate.packageName === target)
if (!app) throw this.actionError(MiniappErrorCode.APP_NOT_FOUND, `Miniapp not found: ${target}`)
if (app.compatibility && app.compatibility.isCompatible === false) {
islandNotifications.emit({
kind: "version_incompatible",
packageName: target,
reason: `${target} is not compatible with the connected glasses`,
metadata: {missingRequired: app.compatibility.missingRequired ?? [], via: "miniapps.invoke"},
timestamp: Date.now(),
})
throw this.actionError(
MiniappErrorCode.APP_NOT_COMPATIBLE,
`${target} is not compatible with the connected glasses`,
)
}
const action = (app.actions ?? []).find((candidate) => candidate.id === actionId)
if (
!action ||
(action.audience === "host" && !allowHostAudience) ||
(backgroundOnly && (!allowHostAudience || action.audience !== "host" || action.lifecycle !== "transient"))
) {
throw this.actionError(MiniappErrorCode.ACTION_NOT_FOUND, `${target} does not declare action "${actionId}"`)
}
let releaseWake: (() => Promise<void>) | undefined
try {
if (action.lifecycle === "transient") {
if (!app.local) {
throw this.actionError(
MiniappErrorCode.WAKE_FAILED,
`transient action wake is unavailable for non-local miniapp ${target}`,
)
}
releaseWake = await this.transientActionWakes.acquire(target)
} else if (!(await this.startInteropApp(target))) {
throw this.actionError(MiniappErrorCode.WAKE_FAILED, `failed to start ${target}`)
}
} catch (error) {
if ((error as {code?: string}).code) throw error
throw this.actionError(MiniappErrorCode.WAKE_FAILED, (error as Error)?.message ?? `failed to wake ${target}`)
}
// The wake waited for CONNECT, but the target could have dropped in the gap
// before delivery — fail fast rather than arming a timer for a call that
// sendToMiniapp would silently drop.
if (!this.connectedApps.has(target)) {
await releaseWake?.()
throw this.actionError(
MiniappErrorCode.WAKE_FAILED,
`${target} disconnected before the action could be delivered`,
)
}
const callId = `act-${Date.now().toString(36)}-${this.actionCallSeq++}`
return new Promise<unknown>((resolve, reject) => {
const timer = BgTimer.setTimeout(() => {
void this.finalizeActionCall(
callId,
false,
undefined,
this.actionError(MiniappErrorCode.ACTION_TIMEOUT, `action "${actionId}" timed out after ${timeoutMs}ms`),
)
}, timeoutMs)
this.actionCalls.set(callId, {targetPackageName: target, timer, resolve, reject, releaseWake})
this.sendToMiniapp(target, {
type: MiniappResponseType.ACTION_CALL,
callId,
actionId,
params,
callerPackageName,
})
})
}
/** The host invokes a miniapp's action, host-only actions included. The host is not represented as a miniapp. */
public invokeActionFromHost(
targetPackageName: string,
actionId: string,
params: Record<string, unknown> = {},
timeoutMs = 10 * 60_000,
): Promise<unknown> {
const boundedTimeout = Math.min(Math.max(timeoutMs, 6_000), 15 * 60_000)
return this.invokeDeclaredAction(HOST_ACTION_CALLER, targetPackageName, actionId, params, boundedTimeout, true)
}
/** `session.actions.invoke` adapter around the shared broker. */
private async handleActionInvoke(
callerPackageName: string,
payload: Record<string, unknown>,
requestId?: string,
): Promise<void> {
const target = payload.targetPackageName as string | undefined
if (!this.requireSystemCaller(callerPackageName, requestId, "invoke", target)) return
const actionId = payload.actionId as string | undefined
if (!target || !actionId) {
this.sendResult(callerPackageName, requestId, false, undefined, {
code: !target ? MiniappErrorCode.APP_NOT_FOUND : MiniappErrorCode.ACTION_NOT_FOUND,
message: !target ? "invoke requires a targetPackageName" : "invoke requires an actionId",
})
return
}
// Floor the timeout at 6s so the host never rejects with ACTION_TIMEOUT before
// the target SDK's handler-registration window closes. A freshly-woken miniapp
// buffers an undelivered ACTION_CALL for HANDLER_WAIT_MS (5s in @mentra/miniapp's
// actions module) waiting for session.actions.handle; a shorter host timeout
// could fire while the target is still registering, then the action would run
// with no caller left to receive its result. 6s = that 5s buffer + 1s for the
// ACTION_RESULT/NO_ACTION_HANDLER reply to travel back. Keep these in sync.
const timeoutMs = Math.min(Math.max(Number(payload.timeoutMs) || 30_000, 6_000), 120_000)
const params = (payload.params as Record<string, unknown> | undefined) ?? {}
try {
const result = await this.invokeDeclaredAction(callerPackageName, target, actionId, params, timeoutMs, false)
this.sendResult(callerPackageName, requestId, true, result ?? null)
this.auditInterop({caller: callerPackageName, op: "invoke", target, actionId, ok: true})
} catch (error) {
const code = (error as {code?: string}).code ?? MiniappErrorCode.INTERNAL
// A target's own error carries its extra fields through to the caller.
this.sendResult(callerPackageName, requestId, false, undefined, {
...((error as {details?: Record<string, unknown>}).details ?? {}),
code,
message: (error as Error)?.message ?? "action invocation failed",
})
this.auditInterop({caller: callerPackageName, op: "invoke", target, actionId, ok: false, errorCode: code})
}
}
/** The target's context is gone: fail its pending invocations and forget its wake leases. */
private clearActionState(packageName: string): void {
this.transientActionWakes.forget(packageName)
for (const [callId, pending] of this.actionCalls) {
if (pending.targetPackageName !== packageName) continue
void this.finalizeActionCall(
callId,
false,
undefined,
this.actionError(MiniappErrorCode.WAKE_FAILED, `${packageName} disconnected during action execution`),
)
}
}
private async finalizeActionCall(
callId: string,
ok: boolean,
result?: unknown,
error?: Error & {code?: string},
): Promise<void> {
const pending = this.actionCalls.get(callId)
if (!pending) return
this.actionCalls.delete(callId)
BgTimer.clearTimeout(pending.timer)
try {
await pending.releaseWake?.()
} catch (releaseError) {
console.warn(`${LOG_TAG}: failed to release transient action wake`, releaseError)
}
if (ok) pending.resolve(result ?? null)
else pending.reject(error ?? this.actionError(MiniappErrorCode.INTERNAL, "action handler error"))
}
/** Target → host: resolve the correlated action invocation. */
private handleActionResult(targetPackageName: string, payload: Record<string, unknown>): void {
const callId = payload.callId as string | undefined
if (!callId) return
const pending = this.actionCalls.get(callId)
// Only the invoked target may resolve this call. callIds are guessable
// (timestamp + seq), so a different connected miniapp must not be able to
// spoof a result/error for someone else's invoke.
if (!pending || pending.targetPackageName !== targetPackageName) return
if (payload.ok === true) {
const result = payload.result
if (this.actionPayloadTooLarge(result)) {
void this.finalizeActionCall(
callId,
false,
undefined,
this.actionError(MiniappErrorCode.PAYLOAD_TOO_LARGE, "action result exceeded the 256 KB cap"),
)
return
}
void this.finalizeActionCall(callId, true, result)
return
}
const payloadError = payload.error as ({code?: string; message?: string} & Record<string, unknown>) | undefined
void this.finalizeActionCall(
callId,
false,
undefined,
this.actionError(
payloadError?.code ?? MiniappErrorCode.INTERNAL,
payloadError?.message ?? "action handler error",
payloadError,
),
)
}
private sendResult(
packageName: string,
requestId: string | undefined,
ok: boolean,
data?: unknown,
error?: {code: string; message: string} & Record<string, unknown>,
): void {
if (!requestId) return
this.sendToMiniapp(
packageName,
{
type: MiniappResponseType.REQUEST_RESULT,
requestId,
ok,
...(data !== undefined ? {data} : {}),
...(error ? {error} : {}),
},
requestId,
)
}
/**
* Send a VISIBILITY_CHANGE push to a miniapp.
*/
public sendVisibilityChange(packageName: string, visibility: "foreground" | "background"): void {
this.sendToMiniapp(packageName, {
type: MiniappResponseType.VISIBILITY_CHANGE,
visibility,
})
}
/**
* Fast foreground liveness check used when a local miniapp UI is opened or
* resumed. The normal watchdog intentionally waits ~30s to avoid killing a
* healthy-but-busy background script. When the user is actively looking at a
* WebView, a stale JSContext reads as "cloud offline" / no captions, so probe
* immediately and reuse the crash-respawn path if no message comes back.
*/
public probeForegroundLiveness(
packageName: string,
reason = "foreground-open",
timeoutMs = FOREGROUND_LIVENESS_PROBE_TIMEOUT_MS,
): void {
const app = this.connectedApps.get(packageName)
if (!app) return
this.clearForegroundProbe(packageName)
const probeStartedAt = Date.now()
this.sendToMiniapp(packageName, {
type: MiniappRequestType.PING,
})
const timerId = BgTimer.setTimeout(() => {
this.foregroundProbeTimers.delete(packageName)
const current = this.connectedApps.get(packageName)
if (!current) return
if (current.lastPongAt >= probeStartedAt) return
// Respawning tears down an ACS call and its hotspot. A busy background during a join
// misses one short ping; leave it to the regular ping loop, which needs several misses.
// Nobody owns the meeting until the `acsJoin` step, so a live SoftAP attempt counts as well:
// respawning during the hotspot or scoped Wi-Fi join cancels the join outright.
if (acsMeetingService.ownerPackage() === packageName || this.hasLiveSoftapAttempt(packageName)) {
console.warn(`${LOG_TAG}: ${packageName} missed a foreground probe (${reason}) during a call; not respawning`)
return
}
console.warn(`${LOG_TAG}: ${packageName} failed foreground liveness probe (${reason}), respawning`)
this.unregisterApp(packageName)
this.onLivenessTimeout?.(packageName)
}, timeoutMs)
this.foregroundProbeTimers.set(packageName, timerId)
}
// ===========================================================================
// Ping / pong liveness
// ===========================================================================
private ensurePingLoop(): void {
if (this.pingIntervalId !== null) return
this.pingIntervalId = BgTimer.setInterval(() => {
this.doPingRound()
}, PING_INTERVAL_MS)
}
private stopPingLoop(): void {
if (this.pingIntervalId !== null) {
BgTimer.clearInterval(this.pingIntervalId)
this.pingIntervalId = null
}
}
private doPingRound(): void {
const toRemove: string[] = []
for (const [packageName, app] of this.connectedApps) {
if (!this.hasLiveSoftapAttempt(packageName)) {
const liveness = advanceMiniappPingLiveness(app.unansweredPingRounds, PING_TIMEOUT_THRESHOLD)
if (liveness.shouldUnregister) {
console.warn(`${LOG_TAG}: ${packageName} missed ${PING_TIMEOUT_THRESHOLD} pings, unregistering`)
toRemove.push(packageName)
continue
}
app.unansweredPingRounds = liveness.unansweredPingRounds
}
// Send PING — SDK auto-replies with PONG
this.sendToMiniapp(packageName, {
type: MiniappRequestType.PING,
})
}
for (const pkg of toRemove) {
this.unregisterApp(pkg)
// Hand the package to the router's respawn machinery — a missed-pings
// death is treated like a crash so the background script comes back.
this.onLivenessTimeout?.(pkg)
}
}
/**
* Called when a PONG is received from a miniapp (or any message, really).
* Updates lastPongAt to keep the app alive.
*/
public handlePong(packageName: string): void {
const app = this.connectedApps.get(packageName)
if (app) {
app.lastPongAt = Date.now()
app.unansweredPingRounds = 0
this.clearForegroundProbe(packageName)
}
}
/** This miniapp's SoftAP join is in flight and has not been cancelled. */
private hasLiveSoftapAttempt(packageName: string): boolean {
return shouldHoldMiniappPingLiveness({
packageName,
softapPackageName: this.softapAttempt?.packageName,
softapCancelled: this.softapAttempt?.cancelled,
})
}
private clearForegroundProbe(packageName: string): void {
const timerId = this.foregroundProbeTimers.get(packageName)
if (timerId == null) return
BgTimer.clearTimeout(timerId)
this.foregroundProbeTimers.delete(packageName)
}
// ===========================================================================
// Lifecycle
// ===========================================================================
public cleanup(): void {
console.log(`${LOG_TAG}: cleanup()`)
// Installs already in flight belong to the ending session: they must
// not activate afterwards, and their open update prompts close unanswered.
this.installSessionEpoch += 1
dismissRunningUpdatePrompts()
this.visibilityUnsubscribe?.()
this.visibilityUnsubscribe = null
this.appStateSubscription?.remove()
this.appStateSubscription = null
this.visiblePackage = null
this.initialized = false
this.stopPingLoop()
// Copy keys since unregisterApp mutates the map
const packageNames = [...this.connectedApps.keys()]
for (const pkg of packageNames) {
this.unregisterApp(pkg)
}
// Belt-and-suspenders: clear any remaining state
const hadButtonPressSubscribers = this.getButtonPressSubscribers().length > 0
this.streamSubscribers.clear()
if (hadButtonPressSubscribers) {
for (const listener of this.buttonPressSubscriberListeners) {
try {
listener([])
} catch (error) {
console.warn(`${LOG_TAG}: button press subscriber listener threw during cleanup:`, error)
}
}
}
this.connectedApps.clear()
this.lastAppliedLocationRate = null
this.recomputeLocationTier()
for (const timerId of this.foregroundProbeTimers.values()) {
BgTimer.clearTimeout(timerId)
}
this.foregroundProbeTimers.clear()
LocalMiniappRuntime.instance = null
}
/**
* Number of currently connected miniapps (for diagnostics).
*/
public get connectedAppCount(): number {
return this.connectedApps.size
}
}
const localMiniappRuntime = LocalMiniappRuntime.getInstance()
export default localMiniappRuntime
/**
* LocalMiniappRuntime
*
* Singleton service that bridges local miniapps (running in WebViews) with
* phone capabilities: display, audio, storage, sensors, LED, etc.
*
* Each miniapp communicates via the @mentra/miniapp envelope protocol.
* This runtime handles request dispatch, stream fan-out, and lifecycle
* management (connect/disconnect/ping).
*/
import {parsePhotoCompression} from "@mentra/cloud-protocol/photo-compression"
import {acquireGlassesHotspot} from "./GlassesHotspotLease"
import {AppState, Platform} from "react-native"
import * as Battery from "expo-battery"
import * as Clipboard from "expo-clipboard"
import * as Location from "expo-location"
import BluetoothSdk, {type RgbLedAction, type RgbLedColor} from "@mentra/bluetooth-sdk"
import {
MiniappErrorCode,
MiniappRequestType,
MiniappResponseType,
MiniappStreamType,
CLOUD_STATUS_STREAM,
parseEnvelope,
serializeEnvelope,
} from "@mentra/miniapp"
import type {MiniappEnvelope} from "@mentra/miniapp"
import {DeviceTypes, getModelCapabilities} from "../types"
import {storage as mmkvStorage} from "../utils/storage/storage"
import {BgTimer} from "../utils/timers"
import devServerBridge from "./DevServerBridge"
import {islandNotifications} from "./NotificationsEmitter"
import {isGlassesConnected, isGlassesReady, waitForGlassesReady} from "./GlassesReadiness"
import {toMiniappConnectionData} from "./GlassesStatusProjection"
import audioPlaybackService from "./AudioPlaybackService"
import {phoneLocationService} from "./PhoneLocationService"
import {useGlassesStore} from "../stores/glasses"
import {useSettingsStore} from "../stores/settings"
import localDisplayManager from "./LocalDisplayManager"
import type {DisplayPayload} from "./LocalDisplayManager"
import headingService from "./HeadingService"
import localSttFallbackCoordinator from "./LocalSttFallbackCoordinator"
import micStateCoordinator from "./MicStateCoordinator"
import {speechActivityService} from "./SpeechActivityService"
import {wakeWordService} from "./WakeWordService"
import micSessionManager, {MIC_SOURCE_CONFLICT, type MicSession} from "./MicSessionManager"
import {ENGINE_ONLY_USE_CASES, MIC_USE_CASES, VOICE_CALL_PACKAGES, type MicUseCase} from "./micPolicy"
import {BlobStore} from "./BlobStore"
import {MiniappSystemActions} from "./MiniappSystemActions"
import {CloudAudioSubscriptionSync} from "./CloudAudioSubscriptionSync"
import {phoneCameraFovCoordinator} from "./PhoneCameraFovCoordinator"
import {fleetEvents} from "./fleet/fleetEvents"
import {phonePhotoCoordinator} from "./PhonePhotoCoordinator"
import {phoneStreamCoordinator} from "./PhoneStreamCoordinator"
import {phoneVideoCoordinator} from "./PhoneVideoCoordinator"
import {runSentenceTtsPipeline} from "./SentenceTtsPipeline"
import {
needsCloud,
needsLocal,
onDeviceServes,
readSpeechProcessing,
targetSource,
UtteranceTracker,
type SpeechProcessing,
type TranscriptionRoutingState,
} from "./TranscriptionRouting"
import {
addStreamProcessing,
transcriptionRegistrations,
TranscriptionSubscriptions,
type TranscriptionStreamEntry,
} from "./TranscriptionSubscriptions"
import {prepareTtsSentences} from "./TtsTextSanitizer"
import {handleWifiAdbRequest} from "./WifiAdbRequest"
import {cloudClientService} from "./CloudClientService"
import {miniappLauncher} from "./MiniappLauncher"
import {
ISLAND_SETTINGS_KEYS,
type CameraFovPreset,
type CameraFovRequest,
type CameraRoiPosition,
type CloudClientStatusSnapshot,
type InteropAuditEvent,
type MiniappAuthToken,
type TtsSynthesisResult,
} from "../runtime/config"
import {
getAnalytics,
getConfigValues,
getMiniappConfiguration,
getUiSeams,
isFeatureEnabled,
isMiniappAvailable,
} from "../runtime/bootstrap"
import {invokeScanQrSeam} from "../runtime/scanQrSeam"
import {invokePhoneWifiSeam} from "../runtime/phoneWifiSeam"
import {