@mentra/engine 3.1.0-dev.94 → 3.1.0-dev.95
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/build/facades/ota.d.ts +1 -1
- package/build/facades/ota.js +1 -1
- package/build/facades/ota.js.map +1 -1
- package/build/generated/releaseMetadata.js +5 -5
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1 -1
- package/build/index.js.map +1 -1
- package/build/services/DisplayProcessor.d.ts +3 -3
- package/build/services/DisplayProcessor.js +3 -3
- package/build/services/DisplayProcessor.js.map +1 -1
- package/build/services/LocalDisplayManager.d.ts +2 -3
- package/build/services/LocalDisplayManager.d.ts.map +1 -1
- package/build/services/LocalDisplayManager.js +2 -3
- package/build/services/LocalDisplayManager.js.map +1 -1
- package/build/services/PhonePhotoCoordinator.js +1 -1
- package/build/services/PhonePhotoCoordinator.js.map +1 -1
- package/build/services/StreamLifecycleController.d.ts +3 -3
- package/build/services/StreamLifecycleController.js +3 -3
- package/build/services/StreamLifecycleController.js.map +1 -1
- package/build/types/applet.d.ts +1 -1
- package/build/types/applet.js +1 -1
- package/build/types/applet.js.map +1 -1
- package/build/types/capabilities/even-realities-g1.d.ts.map +1 -1
- package/build/types/capabilities/even-realities-g1.js +2 -0
- package/build/types/capabilities/even-realities-g1.js.map +1 -1
- package/build/types/capabilities/even-realities-g2.d.ts.map +1 -1
- package/build/types/capabilities/even-realities-g2.js +2 -0
- package/build/types/capabilities/even-realities-g2.js.map +1 -1
- package/build/types/capabilities/mentra-display.d.ts.map +1 -1
- package/build/types/capabilities/mentra-display.js +2 -0
- package/build/types/capabilities/mentra-display.js.map +1 -1
- package/build/types/capabilities/mentra-live.d.ts.map +1 -1
- package/build/types/capabilities/mentra-live.js +2 -0
- package/build/types/capabilities/mentra-live.js.map +1 -1
- package/build/types/capabilities/nimo.d.ts +9 -0
- package/build/types/capabilities/nimo.d.ts.map +1 -0
- package/build/types/capabilities/nimo.js +57 -0
- package/build/types/capabilities/nimo.js.map +1 -0
- package/build/types/capabilities/none.d.ts.map +1 -1
- package/build/types/capabilities/none.js +2 -0
- package/build/types/capabilities/none.js.map +1 -1
- package/build/types/capabilities/simulated-glasses.d.ts.map +1 -1
- package/build/types/capabilities/simulated-glasses.js +2 -0
- package/build/types/capabilities/simulated-glasses.js.map +1 -1
- package/build/types/capabilities/vuzix-z100.d.ts.map +1 -1
- package/build/types/capabilities/vuzix-z100.js +2 -0
- package/build/types/capabilities/vuzix-z100.js.map +1 -1
- package/build/types/enums.d.ts +2 -1
- package/build/types/enums.d.ts.map +1 -1
- package/build/types/enums.js +1 -0
- package/build/types/enums.js.map +1 -1
- package/build/types/hardware.d.ts +3 -2
- package/build/types/hardware.d.ts.map +1 -1
- package/build/types/hardware.js +3 -1
- package/build/types/hardware.js.map +1 -1
- package/build/types/index.d.ts +1 -1
- package/build/types/index.d.ts.map +1 -1
- package/build/types/index.js +1 -1
- package/build/types/index.js.map +1 -1
- package/build/utils/display/composer/ColumnComposer.d.ts +1 -1
- package/build/utils/display/composer/ColumnComposer.js +1 -1
- package/build/utils/display/composer/ColumnComposer.js.map +1 -1
- package/package.json +6 -6
- package/src/facades/ota.ts +1 -1
- package/src/generated/releaseMetadata.ts +5 -5
- package/src/index.ts +1 -0
- package/src/services/DisplayProcessor.ts +3 -3
- package/src/services/LocalDisplayManager.ts +2 -3
- package/src/services/PhonePhotoCoordinator.ts +1 -1
- package/src/services/StreamLifecycleController.ts +3 -3
- package/src/types/applet.ts +1 -1
- package/src/types/capabilities/even-realities-g1.ts +3 -0
- package/src/types/capabilities/even-realities-g2.ts +3 -0
- package/src/types/capabilities/mentra-display.ts +3 -0
- package/src/types/capabilities/mentra-live.ts +3 -0
- package/src/types/capabilities/nimo.ts +59 -0
- package/src/types/capabilities/none.ts +3 -0
- package/src/types/capabilities/simulated-glasses.ts +3 -0
- package/src/types/capabilities/vuzix-z100.ts +3 -0
- package/src/types/enums.ts +1 -0
- package/src/types/hardware.ts +4 -2
- package/src/types/index.ts +1 -0
- package/src/utils/display/composer/ColumnComposer.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LocalDisplayManager.js","sourceRoot":"","sources":["../../src/services/LocalDisplayManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,YAAY,MAAM,gCAAgC,CAAA;AACzD,OAAO,gBAAgB,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AACjD,OAAO,aAAa,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAC,kBAAkB,EAAC,MAAM,oBAAoB,CAAA;AACrD,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AAEjD,OAAO,EAAC,OAAO,EAAC,MAAM,iBAAiB,CAAA;AAmDvC,gFAAgF;AAChF,YAAY;AACZ,gFAAgF;AAEhF,MAAM,OAAO,GAAG,eAAe,CAAA;AAC/B,MAAM,gBAAgB,GAAG,IAAI,CAAA;AAC7B,0EAA0E;AAC1E,2EAA2E;AAC3E,oCAAoC;AACpC,MAAM,0BAA0B,GAAG,MAAM,CAAA;AACzC,yEAAyE;AACzE,MAAM,eAAe,GAAG,aAAa,CAAA;AAErC,0EAA0E;AAC1E,SAAS,cAAc,CAAC,OAAuB;IAC7C,IAAI,OAAO,CAAC,KAAK;QAAE,OAAO,OAAO,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,CAAA;IACpD,OAAO,OAAO,CAAC,MAAM,EAAE,UAAU,KAAK,YAAY,CAAA;AACpD,CAAC;AAED,gFAAgF;AAChF,sBAAsB;AACtB,gFAAgF;AAEhF,MAAM,mBAAmB;IACf,MAAM,CAAC,QAAQ,GAA+B,IAAI,CAAA;IAElD,OAAO,GAAkB,IAAI,CAAA;IAC7B,cAAc,GAAyB,IAAI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,GAAG,IAAI,CAAA;QAC1B,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAA;QACtB,IAAI,CAAC,GAAG,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAA;QAC3B,IAAI,CAAC,wBAAwB,EAAE,EAAE,CAAA;QACjC,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAA;QACpC,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,IAAI,CAAC,mBAAmB,GAAG,KAAK,CAAA;QAChC,aAAa,CAAC,aAAa,EAAE,CAAA;IAC/B,CAAC;IAED,6CAA6C;IACtC,YAAY;QAMjB,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,iBAAiB,EAAE,IAAI,CAAC,cAAc,EAAE,WAAW,IAAI,IAAI;YAC3D,SAAS,EAAE,IAAI,CAAC,cAAc,EAAE,WAAW,IAAI,IAAI;YACnD,SAAS,EAAE,IAAI,CAAC,UAAU,KAAK,IAAI;SACpC,CAAA;IACH,CAAC;;AAGH,MAAM,mBAAmB,GAAG,mBAAmB,CAAC,WAAW,EAAE,CAAA;AAC7D,eAAe,mBAAmB,CAAA;AAClC,OAAO,EAAC,mBAAmB,EAAC,CAAA","sourcesContent":["/**\n * LocalDisplayManager\n *\n * Phone-side arbiter for display requests originating from LOCAL miniapps\n * (the @mentra/miniapp SDK). Mirrors the user-facing behavior of the cloud\n * DisplayManager (cloud/packages/cloud/src/services/layout/DisplayManager6.1.ts)\n * for the features that matter on the phone:\n *\n * - boot message (\"Starting <AppName>…\") with a bounded window\n * - durationMs auto-clear\n * - core-app vs background-app arbitration with a background lock\n *\n * Scope is deliberately local-only. Cloud-originated displays are untouched\n * and may race with local displays during dev; that's acceptable per plan\n * (agents/local-display-manager-plan.md).\n *\n * Display pacing is NOT done here. A JS-side ~300ms throttle used to live in\n * this class, but JS timers (and therefore the throttle's trailing flush) do\n * not fire on schedule while the iOS app is suspended in the background — so\n * under streaming captions, updates accumulated and then flushed in a burst on\n * the next wake. Pacing + last-wins coalescing now live in the native per-device\n * queue (e.g. G2's event-driven EvenHub queue), which drains off the same BLE\n * events that wake the process. This class forwards every request straight\n * through; the native layer collapses redundant frames per display target.\n *\n * The remaining BgTimer use (boot window, durationMs expiry) is timing that\n * does not need sub-second background fidelity.\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk/internal\"\nimport displayProcessor from \"./DisplayProcessor\"\nimport {useDisplayStore} from \"../stores/display\"\nimport sceneRenderer from \"./SceneRenderer\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport {useGlassesStore} from \"../stores/glasses\"\nimport type {SceneElementInput} from \"../utils/display/scene\"\nimport {BgTimer} from \"../utils/timers\"\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface DisplayPayload {\n view?: \"main\" | \"dashboard\" | string\n /** Legacy layout (sugar / old bundles / cloud shapes). Either this or `scene`. */\n layout?: {layoutType: string; [key: string]: unknown}\n /** Scene elements from display.render(). Either this or `layout`. */\n scene?: SceneElementInput[]\n durationMs?: number\n}\n\n/** Outcome delivered to an awaiting render() call (REQUEST_RESULT payload). */\nexport interface DisplayRequestResult {\n status: \"displayed\" | \"blocked\"\n degraded?: boolean\n dropped?: string[]\n reason?: string\n}\n\nexport type DisplayRequestResolver = (result: DisplayRequestResult) => void\n\ninterface ActiveDisplay {\n packageName: string\n processedEvent: Record<string, unknown>\n /** Set when this display is a scene — restore goes through SceneRenderer replay. */\n scene?: SceneElementInput[]\n expiresAt: number | null\n}\n\ninterface BootingApp {\n packageName: string\n displayName: string\n startedAt: number\n timerId: number\n /** Whatever was on the glasses when this boot started, so a boot that times\n * out without the app rendering can restore it instead of blanking a frame\n * another (e.g. foreground) app owns. Null if the glasses were empty. */\n preBoot: ActiveDisplay | null\n}\n\ninterface BackgroundLock {\n packageName: string\n acquiredAt: number\n expiresAt: number\n lastActiveTime: number\n}\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst LOG_TAG = \"LOCAL_DISPLAY\"\nconst BOOT_DURATION_MS = 1500\n// Mirrors cloud lease for a bg app holding the display. The bg app has to\n// keep driving the display to hold the lock; if it goes quiet and the core\n// app wants the screen, we release.\nconst BACKGROUND_LOCK_TIMEOUT_MS = 10_000\n// Sentinel package name used as the \"source\" of the system boot message.\nconst SYSTEM_BOOT_PKG = \"system.boot\"\n\n/** \"Render nothing\" — an empty scene or an explicit clear_view layout. */\nfunction isClearPayload(payload: DisplayPayload): boolean {\n if (payload.scene) return payload.scene.length === 0\n return payload.layout?.layoutType === \"clear_view\"\n}\n\n// =============================================================================\n// LocalDisplayManager\n// =============================================================================\n\nclass LocalDisplayManager {\n private static instance: LocalDisplayManager | null = null\n\n private coreApp: string | null = null\n private coreAppDisplay: ActiveDisplay | null = null\n private currentDisplay: ActiveDisplay | null = null\n private backgroundLock: BackgroundLock | null = null\n\n private bootingApp: BootingApp | null = null\n private bootQueue: Map<string, {payload: DisplayPayload; resolve?: DisplayRequestResolver}> = new Map()\n\n private expiryTimerId: number | null = null\n\n /** Reconnect-replay subscription state (attachToRuntime). */\n private runtimeAttached = false\n private glassesWasConnected = false\n private unsubscribeGlassesStatus: (() => void) | null = null\n\n /** Injectable for tests. */\n private now: () => number = () => Date.now()\n\n private constructor() {}\n\n public static getInstance(): LocalDisplayManager {\n if (!LocalDisplayManager.instance) {\n LocalDisplayManager.instance = new LocalDisplayManager()\n }\n return LocalDisplayManager.instance\n }\n\n // ===========================================================================\n // Lifecycle API (called from MiniappHost)\n // ===========================================================================\n\n /**\n * A new local miniapp just mounted. Start the boot window.\n * Calling this for a different pkg while another is booting cancels the\n * previous boot.\n */\n public onMount(packageName: string, displayName: string): void {\n console.log(`${LOG_TAG}: onMount(${packageName}, \"${displayName}\")`)\n\n // Snapshot whatever's on the glasses BEFORE the boot text overwrites it.\n // registerApp fires onMount for every spawn — including a background app or\n // a crash-respawn while another app is foreground — so a boot that times out\n // without rendering must put the prior frame back rather than blank it.\n // Never snapshot the boot text itself: back-to-back mounts (the autostart\n // restore loop, crash-respawn chains) land while the previous app's\n // \"Starting X…\" is still on the glasses, and endBoot would \"restore\" that\n // stale, expiry-less frame permanently. Across chained boots, inherit the\n // original pre-boot frame instead.\n const inherited = this.bootingApp ? this.bootingApp.preBoot : this.currentDisplay\n const preBoot = inherited?.packageName === SYSTEM_BOOT_PKG ? null : inherited\n\n // Cancel any in-flight boot for a prior app.\n this.cancelBoot()\n\n // Send the boot message directly (bypass arbitration — this is a system\n // display). Goes through sendNow so scene devices render it as a scene:\n // otherwise every app start would be a legacy→scene transition on the\n // glasses (which costs a blanking clear).\n this.sendNow(SYSTEM_BOOT_PKG, {\n view: \"main\",\n layout: {layoutType: \"text_wall\", text: `Starting ${displayName}…`},\n })\n\n const timerId = BgTimer.setTimeout(() => {\n this.endBoot()\n }, BOOT_DURATION_MS)\n\n this.bootingApp = {\n packageName,\n displayName,\n startedAt: this.now(),\n timerId,\n preBoot,\n }\n this.bootQueue.clear()\n }\n\n /**\n * Mark which miniapp is the \"core\" (foreground) app. Pass null when no local\n * miniapp is foreground.\n */\n public onCoreAppChange(packageName: string | null): void {\n if (this.coreApp === packageName) return\n console.log(`${LOG_TAG}: onCoreAppChange(${packageName ?? \"null\"})`)\n\n this.coreApp = packageName\n\n // No core app means no saved frame to restore on the next unmount.\n // Without this, the previous core's last frame can flicker back onto\n // the glasses when the user-initiated clear is followed by an\n // onUnmount that still finds a populated coreAppDisplay.\n if (packageName === null) {\n this.coreAppDisplay = null\n }\n }\n\n /** Report-safe ownership snapshot for incident diagnostics. */\n public getDiagnosticSnapshot(): Record<string, unknown> {\n return {\n coreAppPackageName: this.coreApp,\n currentDisplayPackageName: this.currentDisplay?.packageName ?? null,\n backgroundLockPackageName: this.backgroundLock?.packageName ?? null,\n bootingPackageName: this.bootingApp?.packageName ?? null,\n }\n }\n\n /**\n * A local miniapp is going away. Clean up all state associated with it.\n */\n public onUnmount(packageName: string): void {\n console.log(`${LOG_TAG}: onUnmount(${packageName})`)\n\n // If this was the booting app, cancel boot — and don't strand its\n // \"Starting X…\" text (a system frame with no expiry): put back what the\n // boot covered, or clear.\n if (this.bootingApp?.packageName === packageName) {\n const preBoot = this.bootingApp.preBoot\n this.cancelBoot()\n if (this.currentDisplay?.packageName === SYSTEM_BOOT_PKG) {\n // The preBoot owner may have forfeited its frame during the boot\n // window (a clear parked in the boot queue) — don't resurrect it.\n const ownerQueued = preBoot ? this.bootQueue.get(preBoot.packageName) : undefined\n const preBootForfeited = ownerQueued !== undefined && isClearPayload(ownerQueued.payload)\n if (preBoot && !preBootForfeited && (preBoot.expiresAt === null || preBoot.expiresAt > this.now())) {\n this.restoreDisplay(preBoot)\n } else {\n this.sendClear()\n }\n }\n }\n this.bootQueue.get(packageName)?.resolve?.({status: \"blocked\", reason: \"app stopped\"})\n this.bootQueue.delete(packageName)\n\n // Forget the app's retained scenes — nothing left to replay for it.\n sceneRenderer.clearApp(packageName)\n\n // Release bg lock if this app held it.\n if (this.backgroundLock?.packageName === packageName) {\n this.backgroundLock = null\n }\n\n // Drop the saved core frame if the core's context is going away — the\n // frame belongs to a dead context and must not be restored later. The\n // coreApp POINTER itself is NOT cleared here: it is derived state owned\n // by the apps-store reconciler. A liveness/crash respawn tears the\n // context down (this path) without any store change — the app is still\n // \"running\" — and clearing the pointer here would leave the respawned\n // foreground app arbitrating as background until an unrelated store\n // write happened to re-run the reconciler. Real stops release the slot\n // via the store (running → false → reconciler → onCoreAppChange(null)).\n if (this.coreApp === packageName) {\n this.coreAppDisplay = null\n }\n\n // If this app owned the current on-glasses display, clear it (and maybe\n // restore the core app's display if it still has time left).\n if (this.currentDisplay?.packageName === packageName) {\n this.clearExpiryTimer()\n this.currentDisplay = null\n this.tryRestoreCoreDisplay()\n if (!this.currentDisplay) {\n // Nothing to restore → clear the glasses.\n this.sendClear()\n }\n }\n }\n\n // ===========================================================================\n // Display request API (called from LocalMiniappRuntime.handleDisplay)\n // ===========================================================================\n\n /**\n * A miniapp requested a display. Routes through boot queue, arbitration,\n * and throttle. This is the only public entry point for miniapp display\n * traffic on the local path.\n *\n * `resolve`, when provided (render() requests), is guaranteed to be called\n * exactly once with the request's outcome — including for requests parked in\n * the boot queue (resolved when drained or superseded).\n */\n public request(packageName: string, payload: DisplayPayload, resolve?: DisplayRequestResolver): void {\n // Dashboard view: pass straight through (no throttle/arbitration). Local\n // dashboard rendering is currently a stub on the phone anyway.\n if (payload.view === \"dashboard\") {\n this.sendNow(packageName, payload, resolve)\n return\n }\n\n // During boot, any app's requests go into the queue. If the booting app\n // itself makes its first display call, end boot early and drain.\n if (this.bootingApp) {\n const superseded = this.bootQueue.get(packageName)\n superseded?.resolve?.({status: \"blocked\", reason: \"superseded by a newer frame\"})\n this.bootQueue.set(packageName, {payload, resolve})\n if (this.bootingApp.packageName === packageName) {\n this.endBoot()\n }\n return\n }\n\n this.arbitrateAndSend(packageName, payload, resolve)\n }\n\n /**\n * End a package's temporary display early. If it currently owns the main\n * view, release its background lock and restore the foreground miniapp's\n * saved frame. A dismissal for a package that is no longer visible is a\n * no-op.\n */\n public dismiss(packageName: string): void {\n this.handleExpiry(packageName)\n }\n\n // ===========================================================================\n // Internals — arbitration\n // ===========================================================================\n\n private arbitrateAndSend(packageName: string, payload: DisplayPayload, resolve?: DisplayRequestResolver): void {\n const now = this.now()\n\n // Expire a stale bg lock before arbitrating.\n if (this.backgroundLock && now > this.backgroundLock.expiresAt) {\n this.backgroundLock = null\n }\n\n // A clear (\"render nothing\") means \"I'm done with the display\" — it is a\n // forfeit, not a frame. A background app releases its lock and the core\n // app's still-valid display comes back; treating it as a render instead\n // would RENEW the lock with an empty frame and blank the glasses while\n // still blocking everyone else.\n if (isClearPayload(payload)) {\n this.handleAppClear(packageName, resolve)\n return\n }\n\n const isCore = packageName === this.coreApp\n\n if (isCore) {\n // Save so we can restore later.\n this.coreAppDisplay = {\n packageName,\n processedEvent: {}, // filled by sendNow\n scene: payload.scene,\n expiresAt: payload.durationMs ? now + payload.durationMs : null,\n }\n\n // If a bg app holds the lock AND is currently on the glasses, core is\n // blocked. The saved coreAppDisplay surfaces when the bg app expires\n // or unmounts.\n const bgHoldsAndDisplays =\n this.backgroundLock &&\n this.currentDisplay &&\n this.currentDisplay.packageName === this.backgroundLock.packageName\n if (bgHoldsAndDisplays) {\n resolve?.({status: \"blocked\", reason: \"a background app holds the display\"})\n return\n }\n\n // Core can display. If a bg lock exists but holder isn't actively on\n // the glasses, release it.\n if (this.backgroundLock && !bgHoldsAndDisplays) {\n this.backgroundLock = null\n }\n\n this.sendNow(packageName, payload, resolve)\n return\n }\n\n // Non-core: this is a background app.\n if (this.backgroundLock && this.backgroundLock.packageName !== packageName) {\n // Another bg app already holds the lock — drop.\n resolve?.({status: \"blocked\", reason: \"another background app holds the display\"})\n return\n }\n\n // Acquire or bump the lock.\n if (!this.backgroundLock) {\n this.backgroundLock = {\n packageName,\n acquiredAt: now,\n expiresAt: now + BACKGROUND_LOCK_TIMEOUT_MS,\n lastActiveTime: now,\n }\n } else {\n this.backgroundLock.lastActiveTime = now\n this.backgroundLock.expiresAt = now + BACKGROUND_LOCK_TIMEOUT_MS\n }\n\n this.sendNow(packageName, payload, resolve)\n }\n\n /**\n * An app cleared its display (\"render nothing\"). Same semantics as its\n * frame expiring: give up ownership, restore the core app's still-valid\n * display if there is one, otherwise clear the glasses.\n */\n private handleAppClear(packageName: string, resolve?: DisplayRequestResolver): void {\n // Forget the app's retained scene state — its next render starts fresh.\n sceneRenderer.clearApp(packageName)\n\n if (this.backgroundLock?.packageName === packageName) {\n this.backgroundLock = null\n }\n if (this.coreApp === packageName) {\n this.coreAppDisplay = null\n }\n\n if (this.currentDisplay?.packageName === packageName) {\n this.clearExpiryTimer()\n this.currentDisplay = null\n this.tryRestoreCoreDisplay()\n if (!this.currentDisplay) {\n this.sendClear()\n }\n }\n resolve?.({status: \"displayed\"})\n }\n\n // ===========================================================================\n // Internals — send\n // ===========================================================================\n\n private sendNow(packageName: string, payload: DisplayPayload, resolve?: DisplayRequestResolver): void {\n const expiresAt = payload.durationMs ? this.now() + payload.durationMs : null\n const view = (payload.view === \"dashboard\" ? \"dashboard\" : \"main\") as \"main\" | \"dashboard\"\n\n // Scene requests — and legacy layouts a positioning device can render as a\n // scene (sugar, old bundles) — go through the scene pipeline. Everything\n // else stays on the legacy path.\n let sceneElements = payload.scene ?? null\n if (!sceneElements && payload.layout) {\n const caps = sceneRenderer.currentCapabilities()\n if (caps?.canPosition) {\n sceneElements = sceneRenderer.convertLegacyLayout(payload.layout, caps)\n }\n }\n\n if (sceneElements) {\n this.sendScene(packageName, view, sceneElements, expiresAt, resolve)\n } else if (payload.layout) {\n // This layout bypasses the scene pipeline (clear_view, dashboard_card,\n // unknown types, or a non-positioning device). If this (app, view) had a\n // retained scene, the glasses no longer match it — reset the diff\n // baseline so the next render() repaints from empty instead of skipping\n // \"unchanged\" elements.\n sceneRenderer.resetBaseline(packageName, view)\n const rawEvent: Record<string, unknown> = {\n view: payload.view ?? \"main\",\n layout: payload.layout,\n }\n if (payload.durationMs !== undefined) {\n rawEvent.durationMs = payload.durationMs\n }\n this.sendToNative(packageName, rawEvent, expiresAt)\n resolve?.({status: \"displayed\"})\n } else {\n // A scene payload on a device with no display block at all.\n resolve?.({status: \"blocked\", reason: \"no display connected\"})\n return\n }\n\n // If core app fired, refresh the saved snapshot with the actual processed\n // event so restore uses the wrapped text (legacy) / the retained scene.\n if (packageName === this.coreApp && this.currentDisplay) {\n this.coreAppDisplay = {\n packageName,\n processedEvent: this.currentDisplay.processedEvent,\n scene: this.currentDisplay.scene,\n expiresAt: this.currentDisplay.expiresAt,\n }\n }\n }\n\n /**\n * Send a scene through SceneRenderer. On positioning devices this emits a\n * SceneFrame; on degrade devices SceneRenderer hands back a legacy layout\n * that rides the existing (unchanged) DisplayProcessor path.\n */\n private sendScene(\n packageName: string,\n view: \"main\" | \"dashboard\",\n elements: SceneElementInput[],\n expiresAt: number | null,\n resolve?: DisplayRequestResolver,\n ): void {\n const result = sceneRenderer.emitScene(packageName, view, elements)\n\n if (result.kind === \"no-display\") {\n resolve?.({status: \"blocked\", reason: \"no display connected\"})\n return\n }\n\n if (result.kind === \"legacy\") {\n if (result.layout) {\n this.sendToNative(packageName, {view, layout: result.layout}, expiresAt)\n } else {\n // Scene degraded to nothing (e.g. all-image scene on a text-only\n // device). render() replaces the frame, so nothing means clear.\n this.sendClear()\n }\n resolve?.({status: \"displayed\", degraded: result.degraded, dropped: result.dropped})\n return\n }\n\n this.currentDisplay = {packageName, processedEvent: {}, scene: elements, expiresAt}\n this.clearExpiryTimer()\n if (expiresAt !== null) {\n const delay = Math.max(0, expiresAt - this.now())\n this.expiryTimerId = BgTimer.setTimeout(() => {\n this.expiryTimerId = null\n this.handleExpiry(packageName)\n }, delay)\n }\n resolve?.({status: \"displayed\", degraded: result.degraded, dropped: result.dropped})\n }\n\n private sendToNative(packageName: string, rawEvent: Record<string, unknown>, expiresAt: number | null): void {\n let processedEvent: Record<string, unknown>\n try {\n processedEvent = displayProcessor.processDisplayEvent(rawEvent as any)\n } catch (err) {\n console.error(`${LOG_TAG}: DisplayProcessor error, using raw event:`, err)\n processedEvent = rawEvent\n }\n\n try {\n // The display output path is a direct btsdk call now (was a host sendDisplayEvent\n // hook) so a bare OEM renders to the glasses without wiring it.\n void Promise.resolve(BluetoothSdk.displayEvent(processedEvent)).catch((err) => {\n console.error(`${LOG_TAG}: native display failed:`, err)\n })\n // The mirror store also lives in engine, so display requests update the\n // phone-side preview without any host hook.\n useDisplayStore.getState().setDisplayEvent(JSON.stringify(processedEvent))\n } catch (err) {\n console.error(`${LOG_TAG}: native display failed:`, err)\n }\n\n this.currentDisplay = {packageName, processedEvent, expiresAt}\n\n this.clearExpiryTimer()\n if (expiresAt !== null) {\n const delay = Math.max(0, expiresAt - this.now())\n this.expiryTimerId = BgTimer.setTimeout(() => {\n this.expiryTimerId = null\n this.handleExpiry(packageName)\n }, delay)\n }\n }\n\n private handleExpiry(packageName: string): void {\n // Someone else is on the glasses now — ignore.\n if (!this.currentDisplay || this.currentDisplay.packageName !== packageName) {\n return\n }\n\n // Release the lock if it belonged to this (bg) app.\n if (this.backgroundLock?.packageName === packageName) {\n this.backgroundLock = null\n }\n\n this.currentDisplay = null\n this.tryRestoreCoreDisplay()\n if (!this.currentDisplay) {\n this.sendClear()\n }\n }\n\n private tryRestoreCoreDisplay(): void {\n if (!this.coreAppDisplay) return\n // If the core snapshot has a duration and it's already elapsed, skip.\n if (this.coreAppDisplay.expiresAt !== null && this.now() >= this.coreAppDisplay.expiresAt) {\n this.coreAppDisplay = null\n return\n }\n // Re-send the core's saved display.\n this.restoreDisplay(this.coreAppDisplay)\n }\n\n private sendClear(): void {\n const clearEvent: Record<string, unknown> = {\n view: \"main\",\n layout: {layoutType: \"clear_view\"},\n }\n this.sendToNative(\"system.clear\", clearEvent, null)\n this.currentDisplay = null\n // The glasses main view is now blank: every app's retained scene is\n // replay-only until it re-renders — diffing against it would skip\n // \"unchanged\" elements onto the blank screen.\n sceneRenderer.markViewStale(\"main\")\n }\n\n // ===========================================================================\n // Internals — boot\n // ===========================================================================\n\n private cancelBoot(): void {\n if (!this.bootingApp) return\n BgTimer.clearTimeout(this.bootingApp.timerId)\n this.bootingApp = null\n }\n\n private endBoot(): void {\n if (!this.bootingApp) return\n const preBoot = this.bootingApp.preBoot\n BgTimer.clearTimeout(this.bootingApp.timerId)\n this.bootingApp = null\n\n // Drain the queue: core first, then everyone else. Per-app last wins\n // because the map holds one payload per packageName.\n const queued = Array.from(this.bootQueue.entries())\n this.bootQueue.clear()\n\n const corePayload = this.coreApp ? queued.find(([pkg]) => pkg === this.coreApp) : undefined\n if (corePayload) {\n this.arbitrateAndSend(corePayload[0], corePayload[1].payload, corePayload[1].resolve)\n }\n for (const [pkg, entry] of queued) {\n if (pkg === this.coreApp) continue\n this.arbitrateAndSend(pkg, entry.payload, entry.resolve)\n }\n\n // If the boot text is still on the glasses — nothing was queued, or every\n // drained request lost arbitration — it must not strand: it's a system\n // frame with no expiry. Restore whatever was on the glasses before the\n // boot, else clear. Two reasons NOT to restore: the frame's duration\n // elapsed during the boot window, or its owner FORFEITED it during the\n // window (its final queued intent — the queue keeps last-wins per app —\n // was a clear, which the drain above processed as a forfeit; restoring\n // would resurrect content the clear removed).\n if (this.currentDisplay?.packageName === SYSTEM_BOOT_PKG) {\n const ownerEntry = preBoot ? queued.find(([pkg]) => pkg === preBoot.packageName) : undefined\n const preBootForfeited = ownerEntry !== undefined && isClearPayload(ownerEntry[1].payload)\n if (preBoot && !preBootForfeited && (preBoot.expiresAt === null || preBoot.expiresAt > this.now())) {\n this.restoreDisplay(preBoot)\n } else {\n this.sendClear()\n }\n }\n }\n\n /**\n * Re-push a previously-captured on-glasses frame (e.g. the display a boot\n * window overwrote). Mirrors tryRestoreCoreDisplay: the saved event is already\n * processed, and any remaining duration is recomputed from its expiry.\n */\n private restoreDisplay(saved: ActiveDisplay): void {\n const remaining = saved.expiresAt !== null ? Math.max(0, saved.expiresAt - this.now()) : undefined\n\n // Scene restores must REPLAY (create-based, epoch-bumped): re-emitting the\n // scene through the normal diff would come back all-\"unchanged\" and the\n // device would skip every element (spec §4 — replay is always create-based).\n if (saved.scene) {\n const expiresAt = remaining !== undefined ? this.now() + remaining : null\n if (sceneRenderer.replayApp(saved.packageName, \"main\")) {\n this.currentDisplay = {packageName: saved.packageName, processedEvent: {}, scene: saved.scene, expiresAt}\n this.clearExpiryTimer()\n if (expiresAt !== null) {\n const delay = Math.max(0, expiresAt - this.now())\n this.expiryTimerId = BgTimer.setTimeout(() => {\n this.expiryTimerId = null\n this.handleExpiry(saved.packageName)\n }, delay)\n }\n } else {\n // Retained state gone (app stopped since) — re-render the saved\n // elements as a fresh scene instead.\n this.sendNow(saved.packageName, {view: \"main\", scene: saved.scene, durationMs: remaining})\n }\n return\n }\n\n this.sendNow(saved.packageName, {\n view: \"main\",\n layout: saved.processedEvent.layout as DisplayPayload[\"layout\"],\n durationMs: remaining,\n })\n }\n\n // ===========================================================================\n // Reconnect replay (design doc §3.4.7 — recovery = replay, host-driven)\n // ===========================================================================\n\n /**\n * Subscribe to glasses connection state so the current owner's frame is\n * replayed after a reconnect. Safe to call repeatedly; attaches once. Wired\n * from MantleManager next to displayProcessor.attachToRuntime().\n */\n public attachToRuntime(): void {\n if (this.runtimeAttached) return\n // dev wired this through the (since-removed) glassesStatus runtime hooks;\n // engine reads its own glasses store directly.\n this.glassesWasConnected = isGlassesConnected(useGlassesStore.getState().connection)\n this.unsubscribeGlassesStatus = useGlassesStore.subscribe(() => {\n const connected = isGlassesConnected(useGlassesStore.getState().connection)\n if (connected === this.glassesWasConnected) return\n this.glassesWasConnected = connected\n if (connected) {\n this.replayCurrent()\n }\n })\n this.runtimeAttached = true\n }\n\n /**\n * Re-push the current on-glasses frame after a device recovery. Scenes replay\n * from SceneRenderer's retained state (create-based, epoch-bumped); legacy\n * frames re-send their processed event. Expired frames don't come back.\n */\n public replayCurrent(): void {\n const current = this.currentDisplay\n if (!current) return\n if (current.expiresAt !== null && this.now() >= current.expiresAt) return\n\n console.log(`${LOG_TAG}: replayCurrent(${current.packageName})`)\n if (current.scene) {\n if (!sceneRenderer.replayApp(current.packageName, \"main\")) {\n // Retained state gone (app stopped between disconnect and reconnect).\n this.sendClear()\n }\n } else if (current.processedEvent.layout) {\n this.sendToNative(current.packageName, current.processedEvent, current.expiresAt)\n }\n }\n\n // ===========================================================================\n // Internals — timer helpers\n // ===========================================================================\n\n private clearExpiryTimer(): void {\n if (this.expiryTimerId !== null) {\n BgTimer.clearTimeout(this.expiryTimerId)\n this.expiryTimerId = null\n }\n }\n\n // ===========================================================================\n // Test hooks\n // ===========================================================================\n\n /** Injected clock — tests only. */\n public _setNowForTest(fn: () => number): void {\n this.now = fn\n }\n\n /** Wipe state — tests only. */\n public _resetForTest(): void {\n this.cancelBoot()\n this.clearExpiryTimer()\n this.coreApp = null\n this.coreAppDisplay = null\n this.currentDisplay = null\n this.backgroundLock = null\n this.bootQueue.clear()\n this.now = () => Date.now()\n this.unsubscribeGlassesStatus?.()\n this.unsubscribeGlassesStatus = null\n this.runtimeAttached = false\n this.glassesWasConnected = false\n sceneRenderer._resetForTest()\n }\n\n /** Read-only state snapshot — tests only. */\n public _peekForTest(): {\n coreApp: string | null\n currentDisplayPkg: string | null\n bgLockPkg: string | null\n isBooting: boolean\n } {\n return {\n coreApp: this.coreApp,\n currentDisplayPkg: this.currentDisplay?.packageName ?? null,\n bgLockPkg: this.backgroundLock?.packageName ?? null,\n isBooting: this.bootingApp !== null,\n }\n }\n}\n\nconst localDisplayManager = LocalDisplayManager.getInstance()\nexport default localDisplayManager\nexport {LocalDisplayManager}\n"]}
|
|
1
|
+
{"version":3,"file":"LocalDisplayManager.js","sourceRoot":"","sources":["../../src/services/LocalDisplayManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,YAAY,MAAM,gCAAgC,CAAA;AACzD,OAAO,gBAAgB,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AACjD,OAAO,aAAa,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAC,kBAAkB,EAAC,MAAM,oBAAoB,CAAA;AACrD,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AAEjD,OAAO,EAAC,OAAO,EAAC,MAAM,iBAAiB,CAAA;AAmDvC,gFAAgF;AAChF,YAAY;AACZ,gFAAgF;AAEhF,MAAM,OAAO,GAAG,eAAe,CAAA;AAC/B,MAAM,gBAAgB,GAAG,IAAI,CAAA;AAC7B,0EAA0E;AAC1E,2EAA2E;AAC3E,oCAAoC;AACpC,MAAM,0BAA0B,GAAG,MAAM,CAAA;AACzC,yEAAyE;AACzE,MAAM,eAAe,GAAG,aAAa,CAAA;AAErC,0EAA0E;AAC1E,SAAS,cAAc,CAAC,OAAuB;IAC7C,IAAI,OAAO,CAAC,KAAK;QAAE,OAAO,OAAO,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,C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B;IACxB,aAAa;QAClB,IAAI,CAAC,UAAU,EAAE,CAAA;QACjB,IAAI,CAAC,gBAAgB,EAAE,CAAA;QACvB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;QACnB,IAAI,CAAC,cAAc,GAAG,IAAI,CAAA;QAC1B,IAAI,CAAC,cAAc,GAAG,IAAI,CAAA;QAC1B,IAAI,CAAC,cAAc,GAAG,IAAI,CAAA;QAC1B,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAA;QACtB,IAAI,CAAC,GAAG,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAA;QAC3B,IAAI,CAAC,wBAAwB,EAAE,EAAE,CAAA;QACjC,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAA;QACpC,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,IAAI,CAAC,mBAAmB,GAAG,KAAK,CAAA;QAChC,aAAa,CAAC,aAAa,EAAE,CAAA;IAC/B,CAAC;IAED,6CAA6C;IACtC,YAAY;QAMjB,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,iBAAiB,EAAE,IAAI,CAAC,cAAc,EAAE,WAAW,IAAI,IAAI;YAC3D,SAAS,EAAE,IAAI,CAAC,cAAc,EAAE,WAAW,IAAI,IAAI;YACnD,SAAS,EAAE,IAAI,CAAC,UAAU,KAAK,IAAI;SACpC,CAAA;IACH,CAAC;;AAGH,MAAM,mBAAmB,GAAG,mBAAmB,CAAC,WAAW,EAAE,CAAA;AAC7D,eAAe,mBAAmB,CAAA;AAClC,OAAO,EAAC,mBAAmB,EAAC,CAAA","sourcesContent":["/**\n * LocalDisplayManager\n *\n * Phone-side arbiter for display requests originating from LOCAL miniapps\n * (the @mentra/miniapp SDK). Preserves the retired cloud display manager's\n * user-facing behavior for the features that matter on the phone:\n *\n * - boot message (\"Starting <AppName>…\") with a bounded window\n * - durationMs auto-clear\n * - core-app vs background-app arbitration with a background lock\n *\n * Scope is deliberately local-only. Cloud-originated displays are untouched\n * and may race with local displays during dev; that's acceptable per plan\n * (agents/local-display-manager-plan.md).\n *\n * Display pacing is NOT done here. A JS-side ~300ms throttle used to live in\n * this class, but JS timers (and therefore the throttle's trailing flush) do\n * not fire on schedule while the iOS app is suspended in the background — so\n * under streaming captions, updates accumulated and then flushed in a burst on\n * the next wake. Pacing + last-wins coalescing now live in the native per-device\n * queue (e.g. G2's event-driven EvenHub queue), which drains off the same BLE\n * events that wake the process. This class forwards every request straight\n * through; the native layer collapses redundant frames per display target.\n *\n * The remaining BgTimer use (boot window, durationMs expiry) is timing that\n * does not need sub-second background fidelity.\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk/internal\"\nimport displayProcessor from \"./DisplayProcessor\"\nimport {useDisplayStore} from \"../stores/display\"\nimport sceneRenderer from \"./SceneRenderer\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport {useGlassesStore} from \"../stores/glasses\"\nimport type {SceneElementInput} from \"../utils/display/scene\"\nimport {BgTimer} from \"../utils/timers\"\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface DisplayPayload {\n view?: \"main\" | \"dashboard\" | string\n /** Legacy layout (sugar / old bundles / cloud shapes). Either this or `scene`. */\n layout?: {layoutType: string; [key: string]: unknown}\n /** Scene elements from display.render(). Either this or `layout`. */\n scene?: SceneElementInput[]\n durationMs?: number\n}\n\n/** Outcome delivered to an awaiting render() call (REQUEST_RESULT payload). */\nexport interface DisplayRequestResult {\n status: \"displayed\" | \"blocked\"\n degraded?: boolean\n dropped?: string[]\n reason?: string\n}\n\nexport type DisplayRequestResolver = (result: DisplayRequestResult) => void\n\ninterface ActiveDisplay {\n packageName: string\n processedEvent: Record<string, unknown>\n /** Set when this display is a scene — restore goes through SceneRenderer replay. */\n scene?: SceneElementInput[]\n expiresAt: number | null\n}\n\ninterface BootingApp {\n packageName: string\n displayName: string\n startedAt: number\n timerId: number\n /** Whatever was on the glasses when this boot started, so a boot that times\n * out without the app rendering can restore it instead of blanking a frame\n * another (e.g. foreground) app owns. Null if the glasses were empty. */\n preBoot: ActiveDisplay | null\n}\n\ninterface BackgroundLock {\n packageName: string\n acquiredAt: number\n expiresAt: number\n lastActiveTime: number\n}\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst LOG_TAG = \"LOCAL_DISPLAY\"\nconst BOOT_DURATION_MS = 1500\n// Mirrors cloud lease for a bg app holding the display. The bg app has to\n// keep driving the display to hold the lock; if it goes quiet and the core\n// app wants the screen, we release.\nconst BACKGROUND_LOCK_TIMEOUT_MS = 10_000\n// Sentinel package name used as the \"source\" of the system boot message.\nconst SYSTEM_BOOT_PKG = \"system.boot\"\n\n/** \"Render nothing\" — an empty scene or an explicit clear_view layout. */\nfunction isClearPayload(payload: DisplayPayload): boolean {\n if (payload.scene) return payload.scene.length === 0\n return payload.layout?.layoutType === \"clear_view\"\n}\n\n// =============================================================================\n// LocalDisplayManager\n// =============================================================================\n\nclass LocalDisplayManager {\n private static instance: LocalDisplayManager | null = null\n\n private coreApp: string | null = null\n private coreAppDisplay: ActiveDisplay | null = null\n private currentDisplay: ActiveDisplay | null = null\n private backgroundLock: BackgroundLock | null = null\n\n private bootingApp: BootingApp | null = null\n private bootQueue: Map<string, {payload: DisplayPayload; resolve?: DisplayRequestResolver}> = new Map()\n\n private expiryTimerId: number | null = null\n\n /** Reconnect-replay subscription state (attachToRuntime). */\n private runtimeAttached = false\n private glassesWasConnected = false\n private unsubscribeGlassesStatus: (() => void) | null = null\n\n /** Injectable for tests. */\n private now: () => number = () => Date.now()\n\n private constructor() {}\n\n public static getInstance(): LocalDisplayManager {\n if (!LocalDisplayManager.instance) {\n LocalDisplayManager.instance = new LocalDisplayManager()\n }\n return LocalDisplayManager.instance\n }\n\n // ===========================================================================\n // Lifecycle API (called from MiniappHost)\n // ===========================================================================\n\n /**\n * A new local miniapp just mounted. Start the boot window.\n * Calling this for a different pkg while another is booting cancels the\n * previous boot.\n */\n public onMount(packageName: string, displayName: string): void {\n console.log(`${LOG_TAG}: onMount(${packageName}, \"${displayName}\")`)\n\n // Snapshot whatever's on the glasses BEFORE the boot text overwrites it.\n // registerApp fires onMount for every spawn — including a background app or\n // a crash-respawn while another app is foreground — so a boot that times out\n // without rendering must put the prior frame back rather than blank it.\n // Never snapshot the boot text itself: back-to-back mounts (the autostart\n // restore loop, crash-respawn chains) land while the previous app's\n // \"Starting X…\" is still on the glasses, and endBoot would \"restore\" that\n // stale, expiry-less frame permanently. Across chained boots, inherit the\n // original pre-boot frame instead.\n const inherited = this.bootingApp ? this.bootingApp.preBoot : this.currentDisplay\n const preBoot = inherited?.packageName === SYSTEM_BOOT_PKG ? null : inherited\n\n // Cancel any in-flight boot for a prior app.\n this.cancelBoot()\n\n // Send the boot message directly (bypass arbitration — this is a system\n // display). Goes through sendNow so scene devices render it as a scene:\n // otherwise every app start would be a legacy→scene transition on the\n // glasses (which costs a blanking clear).\n this.sendNow(SYSTEM_BOOT_PKG, {\n view: \"main\",\n layout: {layoutType: \"text_wall\", text: `Starting ${displayName}…`},\n })\n\n const timerId = BgTimer.setTimeout(() => {\n this.endBoot()\n }, BOOT_DURATION_MS)\n\n this.bootingApp = {\n packageName,\n displayName,\n startedAt: this.now(),\n timerId,\n preBoot,\n }\n this.bootQueue.clear()\n }\n\n /**\n * Mark which miniapp is the \"core\" (foreground) app. Pass null when no local\n * miniapp is foreground.\n */\n public onCoreAppChange(packageName: string | null): void {\n if (this.coreApp === packageName) return\n console.log(`${LOG_TAG}: onCoreAppChange(${packageName ?? \"null\"})`)\n\n this.coreApp = packageName\n\n // No core app means no saved frame to restore on the next unmount.\n // Without this, the previous core's last frame can flicker back onto\n // the glasses when the user-initiated clear is followed by an\n // onUnmount that still finds a populated coreAppDisplay.\n if (packageName === null) {\n this.coreAppDisplay = null\n }\n }\n\n /** Report-safe ownership snapshot for incident diagnostics. */\n public getDiagnosticSnapshot(): Record<string, unknown> {\n return {\n coreAppPackageName: this.coreApp,\n currentDisplayPackageName: this.currentDisplay?.packageName ?? null,\n backgroundLockPackageName: this.backgroundLock?.packageName ?? null,\n bootingPackageName: this.bootingApp?.packageName ?? null,\n }\n }\n\n /**\n * A local miniapp is going away. Clean up all state associated with it.\n */\n public onUnmount(packageName: string): void {\n console.log(`${LOG_TAG}: onUnmount(${packageName})`)\n\n // If this was the booting app, cancel boot — and don't strand its\n // \"Starting X…\" text (a system frame with no expiry): put back what the\n // boot covered, or clear.\n if (this.bootingApp?.packageName === packageName) {\n const preBoot = this.bootingApp.preBoot\n this.cancelBoot()\n if (this.currentDisplay?.packageName === SYSTEM_BOOT_PKG) {\n // The preBoot owner may have forfeited its frame during the boot\n // window (a clear parked in the boot queue) — don't resurrect it.\n const ownerQueued = preBoot ? this.bootQueue.get(preBoot.packageName) : undefined\n const preBootForfeited = ownerQueued !== undefined && isClearPayload(ownerQueued.payload)\n if (preBoot && !preBootForfeited && (preBoot.expiresAt === null || preBoot.expiresAt > this.now())) {\n this.restoreDisplay(preBoot)\n } else {\n this.sendClear()\n }\n }\n }\n this.bootQueue.get(packageName)?.resolve?.({status: \"blocked\", reason: \"app stopped\"})\n this.bootQueue.delete(packageName)\n\n // Forget the app's retained scenes — nothing left to replay for it.\n sceneRenderer.clearApp(packageName)\n\n // Release bg lock if this app held it.\n if (this.backgroundLock?.packageName === packageName) {\n this.backgroundLock = null\n }\n\n // Drop the saved core frame if the core's context is going away — the\n // frame belongs to a dead context and must not be restored later. The\n // coreApp POINTER itself is NOT cleared here: it is derived state owned\n // by the apps-store reconciler. A liveness/crash respawn tears the\n // context down (this path) without any store change — the app is still\n // \"running\" — and clearing the pointer here would leave the respawned\n // foreground app arbitrating as background until an unrelated store\n // write happened to re-run the reconciler. Real stops release the slot\n // via the store (running → false → reconciler → onCoreAppChange(null)).\n if (this.coreApp === packageName) {\n this.coreAppDisplay = null\n }\n\n // If this app owned the current on-glasses display, clear it (and maybe\n // restore the core app's display if it still has time left).\n if (this.currentDisplay?.packageName === packageName) {\n this.clearExpiryTimer()\n this.currentDisplay = null\n this.tryRestoreCoreDisplay()\n if (!this.currentDisplay) {\n // Nothing to restore → clear the glasses.\n this.sendClear()\n }\n }\n }\n\n // ===========================================================================\n // Display request API (called from LocalMiniappRuntime.handleDisplay)\n // ===========================================================================\n\n /**\n * A miniapp requested a display. Routes through boot queue, arbitration,\n * and throttle. This is the only public entry point for miniapp display\n * traffic on the local path.\n *\n * `resolve`, when provided (render() requests), is guaranteed to be called\n * exactly once with the request's outcome — including for requests parked in\n * the boot queue (resolved when drained or superseded).\n */\n public request(packageName: string, payload: DisplayPayload, resolve?: DisplayRequestResolver): void {\n // Dashboard view: pass straight through (no throttle/arbitration). Local\n // dashboard rendering is currently a stub on the phone anyway.\n if (payload.view === \"dashboard\") {\n this.sendNow(packageName, payload, resolve)\n return\n }\n\n // During boot, any app's requests go into the queue. If the booting app\n // itself makes its first display call, end boot early and drain.\n if (this.bootingApp) {\n const superseded = this.bootQueue.get(packageName)\n superseded?.resolve?.({status: \"blocked\", reason: \"superseded by a newer frame\"})\n this.bootQueue.set(packageName, {payload, resolve})\n if (this.bootingApp.packageName === packageName) {\n this.endBoot()\n }\n return\n }\n\n this.arbitrateAndSend(packageName, payload, resolve)\n }\n\n /**\n * End a package's temporary display early. If it currently owns the main\n * view, release its background lock and restore the foreground miniapp's\n * saved frame. A dismissal for a package that is no longer visible is a\n * no-op.\n */\n public dismiss(packageName: string): void {\n this.handleExpiry(packageName)\n }\n\n // ===========================================================================\n // Internals — arbitration\n // ===========================================================================\n\n private arbitrateAndSend(packageName: string, payload: DisplayPayload, resolve?: DisplayRequestResolver): void {\n const now = this.now()\n\n // Expire a stale bg lock before arbitrating.\n if (this.backgroundLock && now > this.backgroundLock.expiresAt) {\n this.backgroundLock = null\n }\n\n // A clear (\"render nothing\") means \"I'm done with the display\" — it is a\n // forfeit, not a frame. A background app releases its lock and the core\n // app's still-valid display comes back; treating it as a render instead\n // would RENEW the lock with an empty frame and blank the glasses while\n // still blocking everyone else.\n if (isClearPayload(payload)) {\n this.handleAppClear(packageName, resolve)\n return\n }\n\n const isCore = packageName === this.coreApp\n\n if (isCore) {\n // Save so we can restore later.\n this.coreAppDisplay = {\n packageName,\n processedEvent: {}, // filled by sendNow\n scene: payload.scene,\n expiresAt: payload.durationMs ? now + payload.durationMs : null,\n }\n\n // If a bg app holds the lock AND is currently on the glasses, core is\n // blocked. The saved coreAppDisplay surfaces when the bg app expires\n // or unmounts.\n const bgHoldsAndDisplays =\n this.backgroundLock &&\n this.currentDisplay &&\n this.currentDisplay.packageName === this.backgroundLock.packageName\n if (bgHoldsAndDisplays) {\n resolve?.({status: \"blocked\", reason: \"a background app holds the display\"})\n return\n }\n\n // Core can display. If a bg lock exists but holder isn't actively on\n // the glasses, release it.\n if (this.backgroundLock && !bgHoldsAndDisplays) {\n this.backgroundLock = null\n }\n\n this.sendNow(packageName, payload, resolve)\n return\n }\n\n // Non-core: this is a background app.\n if (this.backgroundLock && this.backgroundLock.packageName !== packageName) {\n // Another bg app already holds the lock — drop.\n resolve?.({status: \"blocked\", reason: \"another background app holds the display\"})\n return\n }\n\n // Acquire or bump the lock.\n if (!this.backgroundLock) {\n this.backgroundLock = {\n packageName,\n acquiredAt: now,\n expiresAt: now + BACKGROUND_LOCK_TIMEOUT_MS,\n lastActiveTime: now,\n }\n } else {\n this.backgroundLock.lastActiveTime = now\n this.backgroundLock.expiresAt = now + BACKGROUND_LOCK_TIMEOUT_MS\n }\n\n this.sendNow(packageName, payload, resolve)\n }\n\n /**\n * An app cleared its display (\"render nothing\"). Same semantics as its\n * frame expiring: give up ownership, restore the core app's still-valid\n * display if there is one, otherwise clear the glasses.\n */\n private handleAppClear(packageName: string, resolve?: DisplayRequestResolver): void {\n // Forget the app's retained scene state — its next render starts fresh.\n sceneRenderer.clearApp(packageName)\n\n if (this.backgroundLock?.packageName === packageName) {\n this.backgroundLock = null\n }\n if (this.coreApp === packageName) {\n this.coreAppDisplay = null\n }\n\n if (this.currentDisplay?.packageName === packageName) {\n this.clearExpiryTimer()\n this.currentDisplay = null\n this.tryRestoreCoreDisplay()\n if (!this.currentDisplay) {\n this.sendClear()\n }\n }\n resolve?.({status: \"displayed\"})\n }\n\n // ===========================================================================\n // Internals — send\n // ===========================================================================\n\n private sendNow(packageName: string, payload: DisplayPayload, resolve?: DisplayRequestResolver): void {\n const expiresAt = payload.durationMs ? this.now() + payload.durationMs : null\n const view = (payload.view === \"dashboard\" ? \"dashboard\" : \"main\") as \"main\" | \"dashboard\"\n\n // Scene requests — and legacy layouts a positioning device can render as a\n // scene (sugar, old bundles) — go through the scene pipeline. Everything\n // else stays on the legacy path.\n let sceneElements = payload.scene ?? null\n if (!sceneElements && payload.layout) {\n const caps = sceneRenderer.currentCapabilities()\n if (caps?.canPosition) {\n sceneElements = sceneRenderer.convertLegacyLayout(payload.layout, caps)\n }\n }\n\n if (sceneElements) {\n this.sendScene(packageName, view, sceneElements, expiresAt, resolve)\n } else if (payload.layout) {\n // This layout bypasses the scene pipeline (clear_view, dashboard_card,\n // unknown types, or a non-positioning device). If this (app, view) had a\n // retained scene, the glasses no longer match it — reset the diff\n // baseline so the next render() repaints from empty instead of skipping\n // \"unchanged\" elements.\n sceneRenderer.resetBaseline(packageName, view)\n const rawEvent: Record<string, unknown> = {\n view: payload.view ?? \"main\",\n layout: payload.layout,\n }\n if (payload.durationMs !== undefined) {\n rawEvent.durationMs = payload.durationMs\n }\n this.sendToNative(packageName, rawEvent, expiresAt)\n resolve?.({status: \"displayed\"})\n } else {\n // A scene payload on a device with no display block at all.\n resolve?.({status: \"blocked\", reason: \"no display connected\"})\n return\n }\n\n // If core app fired, refresh the saved snapshot with the actual processed\n // event so restore uses the wrapped text (legacy) / the retained scene.\n if (packageName === this.coreApp && this.currentDisplay) {\n this.coreAppDisplay = {\n packageName,\n processedEvent: this.currentDisplay.processedEvent,\n scene: this.currentDisplay.scene,\n expiresAt: this.currentDisplay.expiresAt,\n }\n }\n }\n\n /**\n * Send a scene through SceneRenderer. On positioning devices this emits a\n * SceneFrame; on degrade devices SceneRenderer hands back a legacy layout\n * that rides the existing (unchanged) DisplayProcessor path.\n */\n private sendScene(\n packageName: string,\n view: \"main\" | \"dashboard\",\n elements: SceneElementInput[],\n expiresAt: number | null,\n resolve?: DisplayRequestResolver,\n ): void {\n const result = sceneRenderer.emitScene(packageName, view, elements)\n\n if (result.kind === \"no-display\") {\n resolve?.({status: \"blocked\", reason: \"no display connected\"})\n return\n }\n\n if (result.kind === \"legacy\") {\n if (result.layout) {\n this.sendToNative(packageName, {view, layout: result.layout}, expiresAt)\n } else {\n // Scene degraded to nothing (e.g. all-image scene on a text-only\n // device). render() replaces the frame, so nothing means clear.\n this.sendClear()\n }\n resolve?.({status: \"displayed\", degraded: result.degraded, dropped: result.dropped})\n return\n }\n\n this.currentDisplay = {packageName, processedEvent: {}, scene: elements, expiresAt}\n this.clearExpiryTimer()\n if (expiresAt !== null) {\n const delay = Math.max(0, expiresAt - this.now())\n this.expiryTimerId = BgTimer.setTimeout(() => {\n this.expiryTimerId = null\n this.handleExpiry(packageName)\n }, delay)\n }\n resolve?.({status: \"displayed\", degraded: result.degraded, dropped: result.dropped})\n }\n\n private sendToNative(packageName: string, rawEvent: Record<string, unknown>, expiresAt: number | null): void {\n let processedEvent: Record<string, unknown>\n try {\n processedEvent = displayProcessor.processDisplayEvent(rawEvent as any)\n } catch (err) {\n console.error(`${LOG_TAG}: DisplayProcessor error, using raw event:`, err)\n processedEvent = rawEvent\n }\n\n try {\n // The display output path is a direct btsdk call now (was a host sendDisplayEvent\n // hook) so a bare OEM renders to the glasses without wiring it.\n void Promise.resolve(BluetoothSdk.displayEvent(processedEvent)).catch((err) => {\n console.error(`${LOG_TAG}: native display failed:`, err)\n })\n // The mirror store also lives in engine, so display requests update the\n // phone-side preview without any host hook.\n useDisplayStore.getState().setDisplayEvent(JSON.stringify(processedEvent))\n } catch (err) {\n console.error(`${LOG_TAG}: native display failed:`, err)\n }\n\n this.currentDisplay = {packageName, processedEvent, expiresAt}\n\n this.clearExpiryTimer()\n if (expiresAt !== null) {\n const delay = Math.max(0, expiresAt - this.now())\n this.expiryTimerId = BgTimer.setTimeout(() => {\n this.expiryTimerId = null\n this.handleExpiry(packageName)\n }, delay)\n }\n }\n\n private handleExpiry(packageName: string): void {\n // Someone else is on the glasses now — ignore.\n if (!this.currentDisplay || this.currentDisplay.packageName !== packageName) {\n return\n }\n\n // Release the lock if it belonged to this (bg) app.\n if (this.backgroundLock?.packageName === packageName) {\n this.backgroundLock = null\n }\n\n this.currentDisplay = null\n this.tryRestoreCoreDisplay()\n if (!this.currentDisplay) {\n this.sendClear()\n }\n }\n\n private tryRestoreCoreDisplay(): void {\n if (!this.coreAppDisplay) return\n // If the core snapshot has a duration and it's already elapsed, skip.\n if (this.coreAppDisplay.expiresAt !== null && this.now() >= this.coreAppDisplay.expiresAt) {\n this.coreAppDisplay = null\n return\n }\n // Re-send the core's saved display.\n this.restoreDisplay(this.coreAppDisplay)\n }\n\n private sendClear(): void {\n const clearEvent: Record<string, unknown> = {\n view: \"main\",\n layout: {layoutType: \"clear_view\"},\n }\n this.sendToNative(\"system.clear\", clearEvent, null)\n this.currentDisplay = null\n // The glasses main view is now blank: every app's retained scene is\n // replay-only until it re-renders — diffing against it would skip\n // \"unchanged\" elements onto the blank screen.\n sceneRenderer.markViewStale(\"main\")\n }\n\n // ===========================================================================\n // Internals — boot\n // ===========================================================================\n\n private cancelBoot(): void {\n if (!this.bootingApp) return\n BgTimer.clearTimeout(this.bootingApp.timerId)\n this.bootingApp = null\n }\n\n private endBoot(): void {\n if (!this.bootingApp) return\n const preBoot = this.bootingApp.preBoot\n BgTimer.clearTimeout(this.bootingApp.timerId)\n this.bootingApp = null\n\n // Drain the queue: core first, then everyone else. Per-app last wins\n // because the map holds one payload per packageName.\n const queued = Array.from(this.bootQueue.entries())\n this.bootQueue.clear()\n\n const corePayload = this.coreApp ? queued.find(([pkg]) => pkg === this.coreApp) : undefined\n if (corePayload) {\n this.arbitrateAndSend(corePayload[0], corePayload[1].payload, corePayload[1].resolve)\n }\n for (const [pkg, entry] of queued) {\n if (pkg === this.coreApp) continue\n this.arbitrateAndSend(pkg, entry.payload, entry.resolve)\n }\n\n // If the boot text is still on the glasses — nothing was queued, or every\n // drained request lost arbitration — it must not strand: it's a system\n // frame with no expiry. Restore whatever was on the glasses before the\n // boot, else clear. Two reasons NOT to restore: the frame's duration\n // elapsed during the boot window, or its owner FORFEITED it during the\n // window (its final queued intent — the queue keeps last-wins per app —\n // was a clear, which the drain above processed as a forfeit; restoring\n // would resurrect content the clear removed).\n if (this.currentDisplay?.packageName === SYSTEM_BOOT_PKG) {\n const ownerEntry = preBoot ? queued.find(([pkg]) => pkg === preBoot.packageName) : undefined\n const preBootForfeited = ownerEntry !== undefined && isClearPayload(ownerEntry[1].payload)\n if (preBoot && !preBootForfeited && (preBoot.expiresAt === null || preBoot.expiresAt > this.now())) {\n this.restoreDisplay(preBoot)\n } else {\n this.sendClear()\n }\n }\n }\n\n /**\n * Re-push a previously-captured on-glasses frame (e.g. the display a boot\n * window overwrote). Mirrors tryRestoreCoreDisplay: the saved event is already\n * processed, and any remaining duration is recomputed from its expiry.\n */\n private restoreDisplay(saved: ActiveDisplay): void {\n const remaining = saved.expiresAt !== null ? Math.max(0, saved.expiresAt - this.now()) : undefined\n\n // Scene restores must REPLAY (create-based, epoch-bumped): re-emitting the\n // scene through the normal diff would come back all-\"unchanged\" and the\n // device would skip every element (spec §4 — replay is always create-based).\n if (saved.scene) {\n const expiresAt = remaining !== undefined ? this.now() + remaining : null\n if (sceneRenderer.replayApp(saved.packageName, \"main\")) {\n this.currentDisplay = {packageName: saved.packageName, processedEvent: {}, scene: saved.scene, expiresAt}\n this.clearExpiryTimer()\n if (expiresAt !== null) {\n const delay = Math.max(0, expiresAt - this.now())\n this.expiryTimerId = BgTimer.setTimeout(() => {\n this.expiryTimerId = null\n this.handleExpiry(saved.packageName)\n }, delay)\n }\n } else {\n // Retained state gone (app stopped since) — re-render the saved\n // elements as a fresh scene instead.\n this.sendNow(saved.packageName, {view: \"main\", scene: saved.scene, durationMs: remaining})\n }\n return\n }\n\n this.sendNow(saved.packageName, {\n view: \"main\",\n layout: saved.processedEvent.layout as DisplayPayload[\"layout\"],\n durationMs: remaining,\n })\n }\n\n // ===========================================================================\n // Reconnect replay (design doc §3.4.7 — recovery = replay, host-driven)\n // ===========================================================================\n\n /**\n * Subscribe to glasses connection state so the current owner's frame is\n * replayed after a reconnect. Safe to call repeatedly; attaches once. Wired\n * from MantleManager next to displayProcessor.attachToRuntime().\n */\n public attachToRuntime(): void {\n if (this.runtimeAttached) return\n // dev wired this through the (since-removed) glassesStatus runtime hooks;\n // engine reads its own glasses store directly.\n this.glassesWasConnected = isGlassesConnected(useGlassesStore.getState().connection)\n this.unsubscribeGlassesStatus = useGlassesStore.subscribe(() => {\n const connected = isGlassesConnected(useGlassesStore.getState().connection)\n if (connected === this.glassesWasConnected) return\n this.glassesWasConnected = connected\n if (connected) {\n this.replayCurrent()\n }\n })\n this.runtimeAttached = true\n }\n\n /**\n * Re-push the current on-glasses frame after a device recovery. Scenes replay\n * from SceneRenderer's retained state (create-based, epoch-bumped); legacy\n * frames re-send their processed event. Expired frames don't come back.\n */\n public replayCurrent(): void {\n const current = this.currentDisplay\n if (!current) return\n if (current.expiresAt !== null && this.now() >= current.expiresAt) return\n\n console.log(`${LOG_TAG}: replayCurrent(${current.packageName})`)\n if (current.scene) {\n if (!sceneRenderer.replayApp(current.packageName, \"main\")) {\n // Retained state gone (app stopped between disconnect and reconnect).\n this.sendClear()\n }\n } else if (current.processedEvent.layout) {\n this.sendToNative(current.packageName, current.processedEvent, current.expiresAt)\n }\n }\n\n // ===========================================================================\n // Internals — timer helpers\n // ===========================================================================\n\n private clearExpiryTimer(): void {\n if (this.expiryTimerId !== null) {\n BgTimer.clearTimeout(this.expiryTimerId)\n this.expiryTimerId = null\n }\n }\n\n // ===========================================================================\n // Test hooks\n // ===========================================================================\n\n /** Injected clock — tests only. */\n public _setNowForTest(fn: () => number): void {\n this.now = fn\n }\n\n /** Wipe state — tests only. */\n public _resetForTest(): void {\n this.cancelBoot()\n this.clearExpiryTimer()\n this.coreApp = null\n this.coreAppDisplay = null\n this.currentDisplay = null\n this.backgroundLock = null\n this.bootQueue.clear()\n this.now = () => Date.now()\n this.unsubscribeGlassesStatus?.()\n this.unsubscribeGlassesStatus = null\n this.runtimeAttached = false\n this.glassesWasConnected = false\n sceneRenderer._resetForTest()\n }\n\n /** Read-only state snapshot — tests only. */\n public _peekForTest(): {\n coreApp: string | null\n currentDisplayPkg: string | null\n bgLockPkg: string | null\n isBooting: boolean\n } {\n return {\n coreApp: this.coreApp,\n currentDisplayPkg: this.currentDisplay?.packageName ?? null,\n bgLockPkg: this.backgroundLock?.packageName ?? null,\n isBooting: this.bootingApp !== null,\n }\n }\n}\n\nconst localDisplayManager = LocalDisplayManager.getInstance()\nexport default localDisplayManager\nexport {LocalDisplayManager}\n"]}
|
|
@@ -104,7 +104,7 @@ export class PhonePhotoCoordinator {
|
|
|
104
104
|
// to time out. Fail fast with a typed error.
|
|
105
105
|
//
|
|
106
106
|
// We DON'T pre-check `hasCamera` here — the canonical capability data
|
|
107
|
-
// lives in `getModelCapabilities(deviceModel)` from @mentra/
|
|
107
|
+
// lives in `getModelCapabilities(deviceModel)` from @mentra/engine and
|
|
108
108
|
// pulling that into this file would add a cross-package import. If a
|
|
109
109
|
// cameraless device receives the BLE photo command, the glasses-side
|
|
110
110
|
// handler will return a photo_response error within ~1s and the gated
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PhonePhotoCoordinator.js","sourceRoot":"","sources":["../../src/services/PhonePhotoCoordinator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,YAAY,MAAM,gCAAgC,CAAA;AAEzD,OAAO,EAAC,kBAAkB,EAAC,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAC,kBAAkB,EAAC,MAAM,oBAAoB,CAAA;AACrD,OAA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AC;CACF;AAED,kFAAkF;AAClF,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,qBAAqB,EAAE,CAAA","sourcesContent":["/**\n * PhonePhotoCoordinator — owns local-miniapp takePhoto() end-to-end.\n *\n * Architecture:\n * miniapp → SDK → LocalMiniappRuntime → photo runtime hook\n * → coordinator.takePhoto(packageName, opts)\n * ├── (precheck) glasses connected + hasCamera\n * ├── cloudClientService.startManagedPhoto → {requestId, uploadUrl, readUrl} (cloud-v2 runtime presign)\n * ├── BluetoothSdk.requestPhoto(requestId, size, uploadUrl, compress, sound)\n * └── race:\n * - cloudClientService.awaitManagedPhotoReady(requestId) resolves on photo.ready push\n * - BluetoothSdk.requestPhoto rejects if terminal photo_response is an error\n * - handlePhotoError(requestId, code, message) rejects if MantleManager observes\n * the same BLE photo_response error before the native promise crosses the bridge\n *\n * `activeRequests` lets MantleManager's gated `photo_response` listener\n * short-circuit our long-poll with a typed error (CAMERA_BUSY, BATTERY_LOW,\n * etc.) instead of waiting 30s for cloud's timeout.\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk/internal\"\nimport type {PhotoSize, PhotoTransferMethod} from \"@mentra/bluetooth-sdk/internal\"\nimport {cloudClientService} from \"./CloudClientService\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport {useGlassesStore} from \"../stores/glasses\"\n\ninterface PhotoResult {\n photoUrl: string\n mimeType: string\n size: number\n}\n\n/** Map legacy/cloud size names onto the native take_photo enum. */\nfunction normalizePhotoSize(value: unknown): PhotoSize {\n if (typeof value !== \"string\") return \"medium\"\n switch (value) {\n case \"small\":\n return \"low\"\n case \"large\":\n return \"high\"\n case \"full\":\n return \"max\"\n default:\n return ([\"low\", \"medium\", \"high\", \"max\"] as const).includes(value as PhotoSize) ? (value as PhotoSize) : \"medium\"\n }\n}\n\nexport interface PhotoOpts {\n /** Legacy cloud size names are normalized before the native take_photo command. */\n size?: \"low\" | \"medium\" | \"high\" | \"max\" | \"small\" | \"large\" | \"full\"\n mode?: \"photo\" | \"text\"\n /** Select direct-only, phone-relayed BLE, or the default Wi-Fi/BLE fallback policy. */\n transferMethod?: PhotoTransferMethod\n compress?: \"none\" | \"low\" | \"medium\" | \"high\"\n sound?: boolean\n saveToGallery?: boolean\n exposureTimeNs?: number\n iso?: number | null\n aeExposureDivisor?: number\n isoCap?: number\n noiseReduction?: boolean\n edgeEnhancement?: boolean\n /** ZSL preview buffering. */\n zsl?: boolean\n /** MFNR still capture. */\n mfnr?: boolean\n ispDigitalGain?: number\n ispAnalogGain?: string\n}\n\nexport interface PhotoTaken {\n photoUrl: string\n mimeType: string\n size: number\n requestId: string\n}\n\n/** Pipeline stage a photo request failed at — surfaced to the miniapp so a dev\n * sees exactly where it broke, not just a flattened message. */\nexport type PhotoStage = \"presign\" | \"command\" | \"capture\" | \"upload\" | \"push\"\n/** Transport in play at the point of failure. */\nexport type PhotoTransport = \"cloud-rest\" | \"ble\" | \"wifi\" | \"ws\"\n\nexport class PhotoError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n public readonly stage?: PhotoStage,\n public readonly transport?: PhotoTransport,\n ) {\n super(message)\n this.name = \"PhotoError\"\n }\n}\n\nfunction parsePhotoTransferMethod(value: unknown): PhotoTransferMethod | undefined {\n if (value === undefined) return undefined\n if (value === \"auto\" || value === \"direct\" || value === \"ble\") return value\n throw new PhotoError(\n \"INVALID_ARGUMENT\",\n `Invalid transferMethod ${JSON.stringify(value)}. Expected \"auto\", \"direct\", or \"ble\".`,\n )\n}\n\ninterface ActiveRequest {\n packageName: string\n abort: AbortController\n resolve: (r: PhotoResult) => void\n reject: (err: Error) => void\n}\n\n/**\n * Last-resort ceiling for the complete capture + encode + transfer + upload\n * pipeline. This must exceed the managed-photo service's 30s ready-push\n * timeout so the cloud can return its more specific failure first.\n *\n * Text mode commonly spends several seconds detecting/cropping the region and\n * can take another 10s+ to transfer over BLE. A 15s ceiling incorrectly\n * rejected successful captures while their upload was still in progress.\n */\nexport const CAPTURE_PIPELINE_TIMEOUT_MS = 45_000\nexport const CAMERA_WARM_UP_DEFAULT_DURATION_MS = 15_000\nexport const CAMERA_WARM_UP_MAX_DURATION_MS = 60_000\n\nlet bleRequestCounter = 0\n\n/** Short 4-hex-char correlation id sent over BLE instead of the full cloud\n * requestId UUID (wire v2 keeps BLE JSON small). */\nfunction mintBleRequestId(): string {\n bleRequestCounter = (bleRequestCounter + 1) & 0xffff\n return bleRequestCounter.toString(16).padStart(4, \"0\")\n}\n\nfunction toNativeCompression(compress: PhotoOpts[\"compress\"]): \"none\" | \"medium\" | \"heavy\" {\n if (compress === \"high\") return \"heavy\"\n if (compress === \"low\" || compress === \"medium\") return \"medium\"\n return \"none\"\n}\n\nexport class PhonePhotoCoordinator {\n // Cloud requestId → in-flight slot. The gated photo_response listener\n // (DeviceEventRouter) resolves short BLE ids via bleIdToCloud before calling\n // owns() / handlePhotoError().\n private readonly activeRequests = new Map<string, ActiveRequest>()\n /** Short BLE correlation id (4-char hex) → full cloud requestId. */\n private readonly bleIdToCloud = new Map<string, string>()\n private readonly activeWarmUps = new Map<\n string,\n {requestId: string; durationMs: number; expiryTimer?: ReturnType<typeof setTimeout>}\n >()\n\n /** Report-safe camera ownership snapshot for incident diagnostics. */\n getDiagnosticSnapshot(): Record<string, unknown> {\n return {\n captureOwners: [...new Set([...this.activeRequests.values()].map((request) => request.packageName))].sort(),\n warmUpOwners: [...this.activeWarmUps.keys()].sort(),\n activeCaptureCount: this.activeRequests.size,\n }\n }\n\n async takePhoto(packageName: string, opts: PhotoOpts): Promise<PhotoTaken> {\n const transferMethod = parsePhotoTransferMethod(opts.transferMethod)\n\n // Pre-check: if glasses aren't even connected, the BLE photo command\n // would be sent into the void and we'd wait 30s for the cloud long-poll\n // to time out. Fail fast with a typed error.\n //\n // We DON'T pre-check `hasCamera` here — the canonical capability data\n // lives in `getModelCapabilities(deviceModel)` from @mentra/types and\n // pulling that into this file would add a cross-package import. If a\n // cameraless device receives the BLE photo command, the glasses-side\n // handler will return a photo_response error within ~1s and the gated\n // photo_response listener in MantleManager will short-circuit our\n // long-poll. Slower but correct.\n if (!isGlassesConnected(useGlassesStore.getState().connection)) {\n throw new PhotoError(\"GLASSES_NOT_CONNECTED\", \"Glasses are not connected\", \"command\", \"ble\")\n }\n\n // Text-mode sensor resolution is owned by ASG constants; keep cloud metadata on a stable\n // high-capacity tier and let the glasses ignore the public size when mode=text.\n const captureSize = opts.size ?? \"medium\"\n\n // 1) Presign via the cloud-v2 managed-photo service. Local miniapps use\n // ONLY the cloud-v2 path: the runtime presigns upload+read URLs and the\n // phone (as the device controller) delivers the bytes; the legacy\n // backend_url mint is gone from this flow.\n let requestId: string\n let uploadUrl: string\n let readUrl: string\n const flowStarted = performance.now()\n try {\n const presignStarted = performance.now()\n const r = await cloudClientService.startManagedPhoto({\n size: opts.mode === \"text\" ? \"max\" : captureSize,\n })\n const presignMs = Math.round(performance.now() - presignStarted)\n if (typeof __DEV__ !== \"undefined\" && __DEV__) {\n console.debug(\n `[PhonePhotoCoordinator] presign ${presignMs}ms size=${opts.mode === \"text\" ? \"max\" : captureSize} mode=${\n opts.mode ?? \"photo\"\n }`,\n )\n }\n requestId = r.requestId\n uploadUrl = r.uploadUrl\n readUrl = r.readUrl\n } catch (err) {\n throw this.toPhotoError(err, \"PHOTO_REQUEST_FAILED\", \"presign\", \"cloud-rest\")\n }\n\n // 2) Build the outcome Promise FIRST so both resolve+reject handles\n // are wired into activeRequests BEFORE any code path can produce\n // an error. Without this, a fast BLE photo_response (BATTERY_LOW\n // etc.) racing with the Promise constructor could fire\n // handlePhotoError() against a no-op rejectFn and silently drop\n // the error.\n // When the managed-photo upload URL is loopback (the local storage provider\n // reached over `adb reverse`), the glasses cannot reach it over WiFi —\n // localhost on the glasses is the glasses. Force BLE transfer so the phone\n // (which CAN reach the reversed runtime) relays the bytes; a public r2/s3\n // presigned URL stays on \"auto\".\n const isLoopbackUpload = /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|10\\.0\\.2\\.2)\\b/.test(uploadUrl)\n\n const abort = new AbortController()\n const bleRequestId = mintBleRequestId()\n this.bleIdToCloud.set(bleRequestId, requestId)\n\n const outcome = new Promise<PhotoResult>((resolve, reject) => {\n this.activeRequests.set(requestId, {packageName, abort, resolve, reject})\n })\n\n // Last-resort watchdog for a wedged pipeline. The managed-photo ready push\n // normally resolves or rejects first; this only prevents an indefinite hang\n // if both the native terminal response and cloud push disappear.\n const captureWatchdog = setTimeout(() => {\n const e = this.activeRequests.get(requestId)\n if (!e) return\n e.abort.abort()\n e.reject(\n new PhotoError(\n \"CAPTURE_TIMEOUT\",\n \"Photo capture did not complete. The take_photo command, media processing, transfer, or upload may have stalled.\",\n \"capture\",\n isLoopbackUpload ? \"ble\" : \"wifi\",\n ),\n )\n }, CAPTURE_PIPELINE_TIMEOUT_MS)\n // Clear the watchdog on BOTH arms. Not `.finally()`: that would mint a new\n // promise that re-rejects unobserved whenever the photo fails (the caller\n // only awaits `outcome` itself), i.e. an unhandled rejection per failure.\n const clearWatchdog = () => clearTimeout(captureWatchdog)\n void outcome.then(clearWatchdog, clearWatchdog)\n\n // 3) Drive glasses over BLE. requestPhoto now resolves at terminal\n // photo_response success, so run it beside the cloud poll instead of\n // awaiting it before polling. Native defaults transferMethod to \"auto\"\n // (Wi-Fi direct with BLE fallback) unless the miniapp forces BLE.\n try {\n void BluetoothSdk.requestPhoto({\n requestId: bleRequestId,\n appId: packageName,\n size: normalizePhotoSize(captureSize),\n mode: opts.mode ?? \"photo\",\n webhookUrl: uploadUrl,\n authToken: null,\n ...(isLoopbackUpload ? {transferMethod: \"ble\" as const} : transferMethod ? {transferMethod} : {}),\n compress: toNativeCompression(opts.compress),\n save: opts.saveToGallery ?? false,\n sound: opts.sound ?? true,\n exposureTimeNs: opts.exposureTimeNs ?? null,\n iso: opts.iso,\n aeExposureDivisor: opts.aeExposureDivisor,\n isoCap: opts.isoCap,\n noiseReduction: opts.noiseReduction,\n edgeEnhancement: opts.edgeEnhancement,\n ...(opts.zsl != null ? {zsl: opts.zsl} : {}),\n ...(opts.mfnr != null ? {mfnr: opts.mfnr} : {}),\n ispDigitalGain: opts.ispDigitalGain,\n ispAnalogGain: opts.ispAnalogGain,\n }).catch((err) => {\n const e = this.activeRequests.get(requestId)\n if (!e) return\n e.abort.abort()\n e.reject(this.toPhotoError(err, \"BLE_SEND_FAILED\", \"command\", \"ble\"))\n })\n } catch (err) {\n this.activeRequests.delete(requestId)\n this.bleIdToCloud.delete(bleRequestId)\n throw this.toPhotoError(err, \"BLE_SEND_FAILED\", \"command\", \"ble\")\n }\n\n // 4) Await the runtime's photo.ready push (replaces the legacy long-poll).\n // handlePhotoError races against it and uses the same entry to reject\n // first.\n cloudClientService\n .awaitManagedPhotoReady(requestId)\n .then((res) => {\n const e = this.activeRequests.get(requestId)\n if (!e) return // already settled by handlePhotoError\n e.resolve({photoUrl: res.readUrl ?? readUrl, mimeType: \"image/jpeg\", size: -1})\n })\n .catch((err) => {\n const e = this.activeRequests.get(requestId)\n if (e) e.reject(this.toPhotoError(err, \"POLL_FAILED\", \"push\", \"ws\"))\n })\n\n try {\n const result = await outcome\n if (typeof __DEV__ !== \"undefined\" && __DEV__) {\n console.debug(\n `[PhonePhotoCoordinator] takePhoto complete ${Math.round(\n performance.now() - flowStarted,\n )}ms requestId=${requestId}`,\n )\n }\n return {\n photoUrl: result.photoUrl,\n mimeType: result.mimeType,\n size: result.size,\n requestId,\n }\n } finally {\n this.activeRequests.delete(requestId)\n this.bleIdToCloud.delete(bleRequestId)\n }\n }\n\n /** Map a short BLE requestId from photo_response back to the cloud requestId. */\n resolveCloudRequestId(bleOrCloudId: string): string {\n return this.bleIdToCloud.get(bleOrCloudId) ?? bleOrCloudId\n }\n\n /**\n * Pre-warm the glasses camera so the next takePhoto() is near-instant.\n *\n * Pure BLE — NO cloud presign, NO upload, NO long-poll. The phone mints and owns\n * the requestId, sends the warm-up command, and resolves when the camera reports\n * ready (the native promise resolves on the ready status event).\n */\n async warmUpCamera(\n packageName: string,\n opts: {\n size?: \"low\" | \"medium\" | \"high\" | \"max\"\n mode?: \"photo\" | \"text\"\n exposureTimeNs?: number\n durationMs?: number\n zsl?: boolean\n mfnr?: boolean\n },\n ): Promise<void> {\n // Pre-check: if glasses aren't connected, the BLE warm-up command would be\n // sent into the void. Fail fast with a typed error.\n if (!isGlassesConnected(useGlassesStore.getState().connection)) {\n throw new PhotoError(\"GLASSES_NOT_CONNECTED\", \"Glasses are not connected\", \"command\", \"ble\")\n }\n\n let lease: {requestId: string; durationMs: number; expiryTimer?: ReturnType<typeof setTimeout>} | undefined\n try {\n await this.stopWarmUpForApp(packageName)\n const requestId = mintBleRequestId()\n const requestedDuration =\n typeof opts.durationMs === \"number\" && Number.isFinite(opts.durationMs) && opts.durationMs > 0\n ? Math.round(opts.durationMs)\n : CAMERA_WARM_UP_DEFAULT_DURATION_MS\n const durationMs = Math.min(requestedDuration, CAMERA_WARM_UP_MAX_DURATION_MS)\n lease = {requestId, durationMs}\n this.activeWarmUps.set(packageName, lease)\n await BluetoothSdk.warmUpCamera({\n requestId,\n size: normalizePhotoSize(opts.size ?? \"medium\"),\n mode: opts.mode ?? \"photo\",\n exposureTimeNs: opts.exposureTimeNs ?? null,\n durationMs,\n ...(opts.zsl != null ? {zsl: opts.zsl} : {}),\n ...(opts.mfnr != null ? {mfnr: opts.mfnr} : {}),\n })\n if (this.activeWarmUps.get(packageName) === lease) {\n lease.expiryTimer = setTimeout(() => {\n if (this.activeWarmUps.get(packageName) === lease) {\n this.activeWarmUps.delete(packageName)\n }\n }, durationMs)\n }\n } catch (err) {\n if (lease && this.activeWarmUps.get(packageName) === lease) {\n if (lease.expiryTimer) clearTimeout(lease.expiryTimer)\n this.activeWarmUps.delete(packageName)\n }\n throw this.toPhotoError(err, \"WARM_UP_FAILED\", \"command\", \"ble\")\n }\n }\n\n /** Release a miniapp's warm-up even if its original warmUpCamera promise is still opening. */\n async stopWarmUpForApp(packageName: string): Promise<void> {\n const active = this.activeWarmUps.get(packageName)\n if (!active) return\n await BluetoothSdk.stopCameraWarmUp(active.requestId)\n if (this.activeWarmUps.get(packageName) === active) {\n this.activeWarmUps.delete(packageName)\n if (active.expiryTimer) clearTimeout(active.expiryTimer)\n }\n }\n\n /** True iff this requestId (short BLE id or cloud id) is one we're currently waiting on. */\n owns(requestId: string): boolean {\n const cloudId = this.resolveCloudRequestId(requestId)\n return this.activeRequests.has(cloudId)\n }\n\n /**\n * Called by MantleManager's gated photo_response listener when glasses\n * report an error (BATTERY_LOW, CAMERA_BUSY, etc.) for a phone-owned\n * requestId. Rejects the in-flight takePhoto Promise immediately.\n */\n handlePhotoError(requestId: string, errorCode: string, errorMessage: string): void {\n const cloudId = this.resolveCloudRequestId(requestId)\n const entry = this.activeRequests.get(cloudId)\n if (!entry) return\n this.bleIdToCloud.delete(requestId)\n // Abort the in-flight long-poll first so we don't double-resolve.\n entry.abort.abort()\n entry.reject(new PhotoError(errorCode || \"GLASSES_ERROR\", errorMessage || \"Glasses error\", \"capture\", \"ble\"))\n // cloud-v2 pending photo requests TTL out on their own; nothing to free.\n }\n\n private toPhotoError(err: unknown, fallbackCode: string, stage?: PhotoStage, transport?: PhotoTransport): PhotoError {\n if (err instanceof PhotoError) return err\n const code = (err as {code?: string})?.code\n const message = err instanceof Error ? err.message : String(err)\n return new PhotoError(code || fallbackCode, message, stage, transport)\n }\n}\n\n// Singleton — coordinator state is process-wide (mirrors phoneStreamCoordinator).\nexport const phonePhotoCoordinator = new PhonePhotoCoordinator()\n"]}
|
|
1
|
+
{"version":3,"file":"PhonePhotoCoordinator.js","sourceRoot":"","sources":["../../src/services/PhonePhotoCoordinator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,YAAY,MAAM,gCAAgC,CAAA;AAEzD,OAAO,EAAC,kBAAkB,EAAC,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAC,kBAAkB,EAAC,MAAM,oBAAoB,CAAA;AACrD,OAAO,EAAC,eAAe,EAA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kF;AAClF,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,qBAAqB,EAAE,CAAA","sourcesContent":["/**\n * PhonePhotoCoordinator — owns local-miniapp takePhoto() end-to-end.\n *\n * Architecture:\n * miniapp → SDK → LocalMiniappRuntime → photo runtime hook\n * → coordinator.takePhoto(packageName, opts)\n * ├── (precheck) glasses connected + hasCamera\n * ├── cloudClientService.startManagedPhoto → {requestId, uploadUrl, readUrl} (cloud-v2 runtime presign)\n * ├── BluetoothSdk.requestPhoto(requestId, size, uploadUrl, compress, sound)\n * └── race:\n * - cloudClientService.awaitManagedPhotoReady(requestId) resolves on photo.ready push\n * - BluetoothSdk.requestPhoto rejects if terminal photo_response is an error\n * - handlePhotoError(requestId, code, message) rejects if MantleManager observes\n * the same BLE photo_response error before the native promise crosses the bridge\n *\n * `activeRequests` lets MantleManager's gated `photo_response` listener\n * short-circuit our long-poll with a typed error (CAMERA_BUSY, BATTERY_LOW,\n * etc.) instead of waiting 30s for cloud's timeout.\n */\n\nimport BluetoothSdk from \"@mentra/bluetooth-sdk/internal\"\nimport type {PhotoSize, PhotoTransferMethod} from \"@mentra/bluetooth-sdk/internal\"\nimport {cloudClientService} from \"./CloudClientService\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport {useGlassesStore} from \"../stores/glasses\"\n\ninterface PhotoResult {\n photoUrl: string\n mimeType: string\n size: number\n}\n\n/** Map legacy/cloud size names onto the native take_photo enum. */\nfunction normalizePhotoSize(value: unknown): PhotoSize {\n if (typeof value !== \"string\") return \"medium\"\n switch (value) {\n case \"small\":\n return \"low\"\n case \"large\":\n return \"high\"\n case \"full\":\n return \"max\"\n default:\n return ([\"low\", \"medium\", \"high\", \"max\"] as const).includes(value as PhotoSize) ? (value as PhotoSize) : \"medium\"\n }\n}\n\nexport interface PhotoOpts {\n /** Legacy cloud size names are normalized before the native take_photo command. */\n size?: \"low\" | \"medium\" | \"high\" | \"max\" | \"small\" | \"large\" | \"full\"\n mode?: \"photo\" | \"text\"\n /** Select direct-only, phone-relayed BLE, or the default Wi-Fi/BLE fallback policy. */\n transferMethod?: PhotoTransferMethod\n compress?: \"none\" | \"low\" | \"medium\" | \"high\"\n sound?: boolean\n saveToGallery?: boolean\n exposureTimeNs?: number\n iso?: number | null\n aeExposureDivisor?: number\n isoCap?: number\n noiseReduction?: boolean\n edgeEnhancement?: boolean\n /** ZSL preview buffering. */\n zsl?: boolean\n /** MFNR still capture. */\n mfnr?: boolean\n ispDigitalGain?: number\n ispAnalogGain?: string\n}\n\nexport interface PhotoTaken {\n photoUrl: string\n mimeType: string\n size: number\n requestId: string\n}\n\n/** Pipeline stage a photo request failed at — surfaced to the miniapp so a dev\n * sees exactly where it broke, not just a flattened message. */\nexport type PhotoStage = \"presign\" | \"command\" | \"capture\" | \"upload\" | \"push\"\n/** Transport in play at the point of failure. */\nexport type PhotoTransport = \"cloud-rest\" | \"ble\" | \"wifi\" | \"ws\"\n\nexport class PhotoError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n public readonly stage?: PhotoStage,\n public readonly transport?: PhotoTransport,\n ) {\n super(message)\n this.name = \"PhotoError\"\n }\n}\n\nfunction parsePhotoTransferMethod(value: unknown): PhotoTransferMethod | undefined {\n if (value === undefined) return undefined\n if (value === \"auto\" || value === \"direct\" || value === \"ble\") return value\n throw new PhotoError(\n \"INVALID_ARGUMENT\",\n `Invalid transferMethod ${JSON.stringify(value)}. Expected \"auto\", \"direct\", or \"ble\".`,\n )\n}\n\ninterface ActiveRequest {\n packageName: string\n abort: AbortController\n resolve: (r: PhotoResult) => void\n reject: (err: Error) => void\n}\n\n/**\n * Last-resort ceiling for the complete capture + encode + transfer + upload\n * pipeline. This must exceed the managed-photo service's 30s ready-push\n * timeout so the cloud can return its more specific failure first.\n *\n * Text mode commonly spends several seconds detecting/cropping the region and\n * can take another 10s+ to transfer over BLE. A 15s ceiling incorrectly\n * rejected successful captures while their upload was still in progress.\n */\nexport const CAPTURE_PIPELINE_TIMEOUT_MS = 45_000\nexport const CAMERA_WARM_UP_DEFAULT_DURATION_MS = 15_000\nexport const CAMERA_WARM_UP_MAX_DURATION_MS = 60_000\n\nlet bleRequestCounter = 0\n\n/** Short 4-hex-char correlation id sent over BLE instead of the full cloud\n * requestId UUID (wire v2 keeps BLE JSON small). */\nfunction mintBleRequestId(): string {\n bleRequestCounter = (bleRequestCounter + 1) & 0xffff\n return bleRequestCounter.toString(16).padStart(4, \"0\")\n}\n\nfunction toNativeCompression(compress: PhotoOpts[\"compress\"]): \"none\" | \"medium\" | \"heavy\" {\n if (compress === \"high\") return \"heavy\"\n if (compress === \"low\" || compress === \"medium\") return \"medium\"\n return \"none\"\n}\n\nexport class PhonePhotoCoordinator {\n // Cloud requestId → in-flight slot. The gated photo_response listener\n // (DeviceEventRouter) resolves short BLE ids via bleIdToCloud before calling\n // owns() / handlePhotoError().\n private readonly activeRequests = new Map<string, ActiveRequest>()\n /** Short BLE correlation id (4-char hex) → full cloud requestId. */\n private readonly bleIdToCloud = new Map<string, string>()\n private readonly activeWarmUps = new Map<\n string,\n {requestId: string; durationMs: number; expiryTimer?: ReturnType<typeof setTimeout>}\n >()\n\n /** Report-safe camera ownership snapshot for incident diagnostics. */\n getDiagnosticSnapshot(): Record<string, unknown> {\n return {\n captureOwners: [...new Set([...this.activeRequests.values()].map((request) => request.packageName))].sort(),\n warmUpOwners: [...this.activeWarmUps.keys()].sort(),\n activeCaptureCount: this.activeRequests.size,\n }\n }\n\n async takePhoto(packageName: string, opts: PhotoOpts): Promise<PhotoTaken> {\n const transferMethod = parsePhotoTransferMethod(opts.transferMethod)\n\n // Pre-check: if glasses aren't even connected, the BLE photo command\n // would be sent into the void and we'd wait 30s for the cloud long-poll\n // to time out. Fail fast with a typed error.\n //\n // We DON'T pre-check `hasCamera` here — the canonical capability data\n // lives in `getModelCapabilities(deviceModel)` from @mentra/engine and\n // pulling that into this file would add a cross-package import. If a\n // cameraless device receives the BLE photo command, the glasses-side\n // handler will return a photo_response error within ~1s and the gated\n // photo_response listener in MantleManager will short-circuit our\n // long-poll. Slower but correct.\n if (!isGlassesConnected(useGlassesStore.getState().connection)) {\n throw new PhotoError(\"GLASSES_NOT_CONNECTED\", \"Glasses are not connected\", \"command\", \"ble\")\n }\n\n // Text-mode sensor resolution is owned by ASG constants; keep cloud metadata on a stable\n // high-capacity tier and let the glasses ignore the public size when mode=text.\n const captureSize = opts.size ?? \"medium\"\n\n // 1) Presign via the cloud-v2 managed-photo service. Local miniapps use\n // ONLY the cloud-v2 path: the runtime presigns upload+read URLs and the\n // phone (as the device controller) delivers the bytes; the legacy\n // backend_url mint is gone from this flow.\n let requestId: string\n let uploadUrl: string\n let readUrl: string\n const flowStarted = performance.now()\n try {\n const presignStarted = performance.now()\n const r = await cloudClientService.startManagedPhoto({\n size: opts.mode === \"text\" ? \"max\" : captureSize,\n })\n const presignMs = Math.round(performance.now() - presignStarted)\n if (typeof __DEV__ !== \"undefined\" && __DEV__) {\n console.debug(\n `[PhonePhotoCoordinator] presign ${presignMs}ms size=${opts.mode === \"text\" ? \"max\" : captureSize} mode=${\n opts.mode ?? \"photo\"\n }`,\n )\n }\n requestId = r.requestId\n uploadUrl = r.uploadUrl\n readUrl = r.readUrl\n } catch (err) {\n throw this.toPhotoError(err, \"PHOTO_REQUEST_FAILED\", \"presign\", \"cloud-rest\")\n }\n\n // 2) Build the outcome Promise FIRST so both resolve+reject handles\n // are wired into activeRequests BEFORE any code path can produce\n // an error. Without this, a fast BLE photo_response (BATTERY_LOW\n // etc.) racing with the Promise constructor could fire\n // handlePhotoError() against a no-op rejectFn and silently drop\n // the error.\n // When the managed-photo upload URL is loopback (the local storage provider\n // reached over `adb reverse`), the glasses cannot reach it over WiFi —\n // localhost on the glasses is the glasses. Force BLE transfer so the phone\n // (which CAN reach the reversed runtime) relays the bytes; a public r2/s3\n // presigned URL stays on \"auto\".\n const isLoopbackUpload = /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|10\\.0\\.2\\.2)\\b/.test(uploadUrl)\n\n const abort = new AbortController()\n const bleRequestId = mintBleRequestId()\n this.bleIdToCloud.set(bleRequestId, requestId)\n\n const outcome = new Promise<PhotoResult>((resolve, reject) => {\n this.activeRequests.set(requestId, {packageName, abort, resolve, reject})\n })\n\n // Last-resort watchdog for a wedged pipeline. The managed-photo ready push\n // normally resolves or rejects first; this only prevents an indefinite hang\n // if both the native terminal response and cloud push disappear.\n const captureWatchdog = setTimeout(() => {\n const e = this.activeRequests.get(requestId)\n if (!e) return\n e.abort.abort()\n e.reject(\n new PhotoError(\n \"CAPTURE_TIMEOUT\",\n \"Photo capture did not complete. The take_photo command, media processing, transfer, or upload may have stalled.\",\n \"capture\",\n isLoopbackUpload ? \"ble\" : \"wifi\",\n ),\n )\n }, CAPTURE_PIPELINE_TIMEOUT_MS)\n // Clear the watchdog on BOTH arms. Not `.finally()`: that would mint a new\n // promise that re-rejects unobserved whenever the photo fails (the caller\n // only awaits `outcome` itself), i.e. an unhandled rejection per failure.\n const clearWatchdog = () => clearTimeout(captureWatchdog)\n void outcome.then(clearWatchdog, clearWatchdog)\n\n // 3) Drive glasses over BLE. requestPhoto now resolves at terminal\n // photo_response success, so run it beside the cloud poll instead of\n // awaiting it before polling. Native defaults transferMethod to \"auto\"\n // (Wi-Fi direct with BLE fallback) unless the miniapp forces BLE.\n try {\n void BluetoothSdk.requestPhoto({\n requestId: bleRequestId,\n appId: packageName,\n size: normalizePhotoSize(captureSize),\n mode: opts.mode ?? \"photo\",\n webhookUrl: uploadUrl,\n authToken: null,\n ...(isLoopbackUpload ? {transferMethod: \"ble\" as const} : transferMethod ? {transferMethod} : {}),\n compress: toNativeCompression(opts.compress),\n save: opts.saveToGallery ?? false,\n sound: opts.sound ?? true,\n exposureTimeNs: opts.exposureTimeNs ?? null,\n iso: opts.iso,\n aeExposureDivisor: opts.aeExposureDivisor,\n isoCap: opts.isoCap,\n noiseReduction: opts.noiseReduction,\n edgeEnhancement: opts.edgeEnhancement,\n ...(opts.zsl != null ? {zsl: opts.zsl} : {}),\n ...(opts.mfnr != null ? {mfnr: opts.mfnr} : {}),\n ispDigitalGain: opts.ispDigitalGain,\n ispAnalogGain: opts.ispAnalogGain,\n }).catch((err) => {\n const e = this.activeRequests.get(requestId)\n if (!e) return\n e.abort.abort()\n e.reject(this.toPhotoError(err, \"BLE_SEND_FAILED\", \"command\", \"ble\"))\n })\n } catch (err) {\n this.activeRequests.delete(requestId)\n this.bleIdToCloud.delete(bleRequestId)\n throw this.toPhotoError(err, \"BLE_SEND_FAILED\", \"command\", \"ble\")\n }\n\n // 4) Await the runtime's photo.ready push (replaces the legacy long-poll).\n // handlePhotoError races against it and uses the same entry to reject\n // first.\n cloudClientService\n .awaitManagedPhotoReady(requestId)\n .then((res) => {\n const e = this.activeRequests.get(requestId)\n if (!e) return // already settled by handlePhotoError\n e.resolve({photoUrl: res.readUrl ?? readUrl, mimeType: \"image/jpeg\", size: -1})\n })\n .catch((err) => {\n const e = this.activeRequests.get(requestId)\n if (e) e.reject(this.toPhotoError(err, \"POLL_FAILED\", \"push\", \"ws\"))\n })\n\n try {\n const result = await outcome\n if (typeof __DEV__ !== \"undefined\" && __DEV__) {\n console.debug(\n `[PhonePhotoCoordinator] takePhoto complete ${Math.round(\n performance.now() - flowStarted,\n )}ms requestId=${requestId}`,\n )\n }\n return {\n photoUrl: result.photoUrl,\n mimeType: result.mimeType,\n size: result.size,\n requestId,\n }\n } finally {\n this.activeRequests.delete(requestId)\n this.bleIdToCloud.delete(bleRequestId)\n }\n }\n\n /** Map a short BLE requestId from photo_response back to the cloud requestId. */\n resolveCloudRequestId(bleOrCloudId: string): string {\n return this.bleIdToCloud.get(bleOrCloudId) ?? bleOrCloudId\n }\n\n /**\n * Pre-warm the glasses camera so the next takePhoto() is near-instant.\n *\n * Pure BLE — NO cloud presign, NO upload, NO long-poll. The phone mints and owns\n * the requestId, sends the warm-up command, and resolves when the camera reports\n * ready (the native promise resolves on the ready status event).\n */\n async warmUpCamera(\n packageName: string,\n opts: {\n size?: \"low\" | \"medium\" | \"high\" | \"max\"\n mode?: \"photo\" | \"text\"\n exposureTimeNs?: number\n durationMs?: number\n zsl?: boolean\n mfnr?: boolean\n },\n ): Promise<void> {\n // Pre-check: if glasses aren't connected, the BLE warm-up command would be\n // sent into the void. Fail fast with a typed error.\n if (!isGlassesConnected(useGlassesStore.getState().connection)) {\n throw new PhotoError(\"GLASSES_NOT_CONNECTED\", \"Glasses are not connected\", \"command\", \"ble\")\n }\n\n let lease: {requestId: string; durationMs: number; expiryTimer?: ReturnType<typeof setTimeout>} | undefined\n try {\n await this.stopWarmUpForApp(packageName)\n const requestId = mintBleRequestId()\n const requestedDuration =\n typeof opts.durationMs === \"number\" && Number.isFinite(opts.durationMs) && opts.durationMs > 0\n ? Math.round(opts.durationMs)\n : CAMERA_WARM_UP_DEFAULT_DURATION_MS\n const durationMs = Math.min(requestedDuration, CAMERA_WARM_UP_MAX_DURATION_MS)\n lease = {requestId, durationMs}\n this.activeWarmUps.set(packageName, lease)\n await BluetoothSdk.warmUpCamera({\n requestId,\n size: normalizePhotoSize(opts.size ?? \"medium\"),\n mode: opts.mode ?? \"photo\",\n exposureTimeNs: opts.exposureTimeNs ?? null,\n durationMs,\n ...(opts.zsl != null ? {zsl: opts.zsl} : {}),\n ...(opts.mfnr != null ? {mfnr: opts.mfnr} : {}),\n })\n if (this.activeWarmUps.get(packageName) === lease) {\n lease.expiryTimer = setTimeout(() => {\n if (this.activeWarmUps.get(packageName) === lease) {\n this.activeWarmUps.delete(packageName)\n }\n }, durationMs)\n }\n } catch (err) {\n if (lease && this.activeWarmUps.get(packageName) === lease) {\n if (lease.expiryTimer) clearTimeout(lease.expiryTimer)\n this.activeWarmUps.delete(packageName)\n }\n throw this.toPhotoError(err, \"WARM_UP_FAILED\", \"command\", \"ble\")\n }\n }\n\n /** Release a miniapp's warm-up even if its original warmUpCamera promise is still opening. */\n async stopWarmUpForApp(packageName: string): Promise<void> {\n const active = this.activeWarmUps.get(packageName)\n if (!active) return\n await BluetoothSdk.stopCameraWarmUp(active.requestId)\n if (this.activeWarmUps.get(packageName) === active) {\n this.activeWarmUps.delete(packageName)\n if (active.expiryTimer) clearTimeout(active.expiryTimer)\n }\n }\n\n /** True iff this requestId (short BLE id or cloud id) is one we're currently waiting on. */\n owns(requestId: string): boolean {\n const cloudId = this.resolveCloudRequestId(requestId)\n return this.activeRequests.has(cloudId)\n }\n\n /**\n * Called by MantleManager's gated photo_response listener when glasses\n * report an error (BATTERY_LOW, CAMERA_BUSY, etc.) for a phone-owned\n * requestId. Rejects the in-flight takePhoto Promise immediately.\n */\n handlePhotoError(requestId: string, errorCode: string, errorMessage: string): void {\n const cloudId = this.resolveCloudRequestId(requestId)\n const entry = this.activeRequests.get(cloudId)\n if (!entry) return\n this.bleIdToCloud.delete(requestId)\n // Abort the in-flight long-poll first so we don't double-resolve.\n entry.abort.abort()\n entry.reject(new PhotoError(errorCode || \"GLASSES_ERROR\", errorMessage || \"Glasses error\", \"capture\", \"ble\"))\n // cloud-v2 pending photo requests TTL out on their own; nothing to free.\n }\n\n private toPhotoError(err: unknown, fallbackCode: string, stage?: PhotoStage, transport?: PhotoTransport): PhotoError {\n if (err instanceof PhotoError) return err\n const code = (err as {code?: string})?.code\n const message = err instanceof Error ? err.message : String(err)\n return new PhotoError(code || fallbackCode, message, stage, transport)\n }\n}\n\n// Singleton — coordinator state is process-wide (mirrors phoneStreamCoordinator).\nexport const phonePhotoCoordinator = new PhonePhotoCoordinator()\n"]}
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
* `setActive(true)` starts the timer; each tick sends a keep-alive with a
|
|
4
4
|
* fresh ackId; `maxMissedAcks` consecutive timeouts fire `onTimeout`.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* Phone-owned successor to the retired cloud stream lifecycle controller.
|
|
7
|
+
* It uses the local `LifecycleLogger` interface because pino is not a phone
|
|
8
|
+
* dependency.
|
|
9
9
|
*/
|
|
10
10
|
export interface LifecycleLogger {
|
|
11
11
|
child(bindings: Record<string, unknown>): LifecycleLogger;
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
* `setActive(true)` starts the timer; each tick sends a keep-alive with a
|
|
4
4
|
* fresh ackId; `maxMissedAcks` consecutive timeouts fire `onTimeout`.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* Phone-owned successor to the retired cloud stream lifecycle controller.
|
|
7
|
+
* It uses the local `LifecycleLogger` interface because pino is not a phone
|
|
8
|
+
* dependency.
|
|
9
9
|
*/
|
|
10
10
|
/**
|
|
11
11
|
* Drives RTMP stream liveliness checks. Activate to start the heartbeat;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StreamLifecycleController.js","sourceRoot":"","sources":["../../src/services/StreamLifecycleController.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAgCH;;;;;GAKG;AACH,MAAM,OAAO,yBAAyB;IAkBjB;IAjBX,cAAc,CAAiC;IAC/C,WAAW,GAAgC,IAAI,GAAG,EAAE,CAAA;IACpD,UAAU,GAAG,CAAC,CAAA;IACd,cAAc,CAAQ;IACtB,MAAM,GAAG,KAAK,CAAA;IACd,QAAQ,GAAG,KAAK,CAAA;IAEP,MAAM,CAAiB;IACvB,QAAQ,CAAQ;IAChB,mBAAmB,CAAQ;IAC3B,YAAY,CAAQ;IACpB,aAAa,CAAQ;IACrB,mBAAmB,CAAgB;IACnC,GAAG,CAAc;IAElC,YACE,OAA+B,EACd,SAAmC;QAAnC,cAAS,GAAT,SAAS,CAA0B;QAEpD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAC,SAAS,EAAE,iBAAiB,EAAC,CAAC,CAAA;QAClE,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAA;QAChC,IAAI,CAAC,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAA;QACtD,I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","sourcesContent":["/**\n * Drives RTMP stream liveliness checks via a keep-alive heartbeat:\n * `setActive(true)` starts the timer; each tick sends a keep-alive with a\n * fresh ackId; `maxMissedAcks` consecutive timeouts fire `onTimeout`.\n *\n * Mirror of `cloud/packages/cloud/src/services/streaming/StreamLifecycleController.ts`\n * — kept byte-equivalent except for the `LifecycleLogger` interface (pino\n * isn't a phone dep). Behavior changes must land in both files.\n */\n\nexport interface LifecycleLogger {\n child(bindings: Record<string, unknown>): LifecycleLogger\n debug(...args: unknown[]): void\n warn(...args: unknown[]): void\n error(...args: unknown[]): void\n}\n\ninterface StreamLifecycleCallbacks {\n sendKeepAlive: (ackId: string) => Promise<void> | void\n onTimeout: () => Promise<void> | void\n onKeepAliveSent?: (ackId: string) => void\n onKeepAliveAcked?: (ackId: string, ageMs: number) => void\n onKeepAliveMissed?: (ackId: string, ageMs: number, missedCount: number) => void\n}\n\nexport interface StreamLifecycleOptions {\n logger: LifecycleLogger\n streamId: string\n keepAliveIntervalMs: number\n ackTimeoutMs: number\n maxMissedAcks: number\n shouldSendKeepAlive?: () => boolean\n now?: () => number\n}\n\ninterface PendingAckInfo {\n sentAt: number\n timeout: ReturnType<typeof setTimeout>\n}\n\n/**\n * Drives RTMP stream liveliness checks. Activate to start the heartbeat;\n * each tick sends a keep-alive with a fresh ackId and arms a timeout. When\n * `maxMissedAcks` consecutive timeouts fire, `onTimeout` is invoked and the\n * caller is expected to tear the stream down.\n */\nexport class StreamLifecycleController {\n private keepAliveTimer?: ReturnType<typeof setInterval>\n private pendingAcks: Map<string, PendingAckInfo> = new Map()\n private missedAcks = 0\n private lastActivityMs: number\n private active = false\n private disposed = false\n\n private readonly logger: LifecycleLogger\n private readonly streamId: string\n private readonly keepAliveIntervalMs: number\n private readonly ackTimeoutMs: number\n private readonly maxMissedAcks: number\n private readonly shouldSendKeepAlive?: () => boolean\n private readonly now: () => number\n\n constructor(\n options: StreamLifecycleOptions,\n private readonly callbacks: StreamLifecycleCallbacks,\n ) {\n this.logger = options.logger.child({component: \"StreamLifecycle\"})\n this.streamId = options.streamId\n this.keepAliveIntervalMs = options.keepAliveIntervalMs\n this.ackTimeoutMs = options.ackTimeoutMs\n this.maxMissedAcks = options.maxMissedAcks\n this.shouldSendKeepAlive = options.shouldSendKeepAlive\n this.now = options.now ?? (() => Date.now())\n this.lastActivityMs = this.now()\n }\n\n setActive(active: boolean): void {\n if (this.disposed || this.active === active) return\n\n this.logger.debug({streamId: this.streamId, active}, \"Updating lifecycle active state\")\n\n this.active = active\n if (active) {\n this.startTimer()\n } else {\n this.stopTimer()\n this.clearPendingAcks()\n this.missedAcks = 0\n }\n }\n\n recordActivity(): void {\n this.lastActivityMs = this.now()\n this.missedAcks = 0\n }\n\n handleAck(ackId: string): void {\n if (this.disposed) return\n\n const ackInfo = this.pendingAcks.get(ackId)\n if (!ackInfo) {\n this.logger.warn({streamId: this.streamId, ackId}, \"Received unknown keep-alive ACK\")\n return\n }\n\n clearTimeout(ackInfo.timeout)\n this.pendingAcks.delete(ackId)\n this.recordActivity()\n\n this.callbacks.onKeepAliveAcked?.(ackId, this.now() - ackInfo.sentAt)\n }\n\n dispose(): void {\n if (this.disposed) return\n\n this.disposed = true\n this.stopTimer()\n this.clearPendingAcks()\n this.logger.debug({streamId: this.streamId}, \"Lifecycle disposed\")\n }\n\n getLastActivityMs(): number {\n return this.lastActivityMs\n }\n\n private startTimer(): void {\n if (this.keepAliveTimer) return\n this.keepAliveTimer = setInterval(() => {\n void this.tick()\n }, this.keepAliveIntervalMs)\n this.logger.debug({streamId: this.streamId}, \"Keep-alive timer started\")\n }\n\n private stopTimer(): void {\n if (this.keepAliveTimer) {\n clearInterval(this.keepAliveTimer)\n this.keepAliveTimer = undefined\n this.logger.debug({streamId: this.streamId}, \"Keep-alive timer stopped\")\n }\n }\n\n private async tick(): Promise<void> {\n if (this.disposed || !this.active) return\n\n if (this.shouldSendKeepAlive && !this.shouldSendKeepAlive()) {\n this.logger.warn(\n {streamId: this.streamId},\n \"Skipping keep-alive send because transport is unavailable\",\n )\n return\n }\n\n const ackId = this.createAckId()\n const sentAt = this.now()\n\n const timeout = setTimeout(() => {\n this.onAckTimeout(ackId, sentAt)\n }, this.ackTimeoutMs)\n\n this.pendingAcks.set(ackId, {sentAt, timeout})\n this.callbacks.onKeepAliveSent?.(ackId)\n\n try {\n await this.callbacks.sendKeepAlive(ackId)\n } catch (error) {\n this.logger.error({streamId: this.streamId, ackId, error}, \"Error sending keep-alive\")\n }\n }\n\n private onAckTimeout(ackId: string, sentAt: number): void {\n if (this.disposed) return\n\n // Race guard: handleAck may have processed the ACK between the timeout\n // being scheduled and this callback running. In that case the ackId is\n // no longer pending — counting it as missed would falsely escalate.\n if (!this.pendingAcks.has(ackId)) return\n\n this.pendingAcks.delete(ackId)\n this.missedAcks += 1\n const ageMs = this.now() - sentAt\n\n this.logger.warn(\n {streamId: this.streamId, ackId, missedAcks: this.missedAcks, ageMs},\n \"Keep-alive ACK timeout\",\n )\n\n this.callbacks.onKeepAliveMissed?.(ackId, ageMs, this.missedAcks)\n\n if (this.missedAcks >= this.maxMissedAcks) {\n this.logger.error(\n {\n streamId: this.streamId,\n missedAcks: this.missedAcks,\n maxMissedAcks: this.maxMissedAcks,\n },\n \"Maximum missed ACKs reached; triggering timeout\",\n )\n\n void this.callbacks.onTimeout()\n }\n }\n\n private clearPendingAcks(): void {\n for (const {timeout} of this.pendingAcks.values()) {\n clearTimeout(timeout)\n }\n this.pendingAcks.clear()\n }\n\n private createAckId(): string {\n return `a${this.now().toString(36).slice(-5)}`\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"StreamLifecycleController.js","sourceRoot":"","sources":["../../src/services/StreamLifecycleController.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAgCH;;;;;GAKG;AACH,MAAM,OAAO,yBAAyB;IAkBjB;IAjBX,cAAc,CAAiC;IAC/C,WAAW,GAAgC,IAAI,GAAG,EAAE,CAAA;IACpD,UAAU,GAAG,CAAC,CAAA;IACd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AAU;gBAC3B,aAAa,EAAE,IAAI,CAAC,aAAa;aAClC,EACD,iDAAiD,CAClD,CAAA;YAED,KAAK,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,CAAA;QACjC,CAAC;IACH,CAAC;IAEO,gBAAgB;QACtB,KAAK,MAAM,EAAC,OAAO,EAAC,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,CAAC;YAClD,YAAY,CAAC,OAAO,CAAC,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAA;IAC1B,CAAC;IAEO,WAAW;QACjB,OAAO,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;IAChD,CAAC;CACF","sourcesContent":["/**\n * Drives RTMP stream liveliness checks via a keep-alive heartbeat:\n * `setActive(true)` starts the timer; each tick sends a keep-alive with a\n * fresh ackId; `maxMissedAcks` consecutive timeouts fire `onTimeout`.\n *\n * Phone-owned successor to the retired cloud stream lifecycle controller.\n * It uses the local `LifecycleLogger` interface because pino is not a phone\n * dependency.\n */\n\nexport interface LifecycleLogger {\n child(bindings: Record<string, unknown>): LifecycleLogger\n debug(...args: unknown[]): void\n warn(...args: unknown[]): void\n error(...args: unknown[]): void\n}\n\ninterface StreamLifecycleCallbacks {\n sendKeepAlive: (ackId: string) => Promise<void> | void\n onTimeout: () => Promise<void> | void\n onKeepAliveSent?: (ackId: string) => void\n onKeepAliveAcked?: (ackId: string, ageMs: number) => void\n onKeepAliveMissed?: (ackId: string, ageMs: number, missedCount: number) => void\n}\n\nexport interface StreamLifecycleOptions {\n logger: LifecycleLogger\n streamId: string\n keepAliveIntervalMs: number\n ackTimeoutMs: number\n maxMissedAcks: number\n shouldSendKeepAlive?: () => boolean\n now?: () => number\n}\n\ninterface PendingAckInfo {\n sentAt: number\n timeout: ReturnType<typeof setTimeout>\n}\n\n/**\n * Drives RTMP stream liveliness checks. Activate to start the heartbeat;\n * each tick sends a keep-alive with a fresh ackId and arms a timeout. When\n * `maxMissedAcks` consecutive timeouts fire, `onTimeout` is invoked and the\n * caller is expected to tear the stream down.\n */\nexport class StreamLifecycleController {\n private keepAliveTimer?: ReturnType<typeof setInterval>\n private pendingAcks: Map<string, PendingAckInfo> = new Map()\n private missedAcks = 0\n private lastActivityMs: number\n private active = false\n private disposed = false\n\n private readonly logger: LifecycleLogger\n private readonly streamId: string\n private readonly keepAliveIntervalMs: number\n private readonly ackTimeoutMs: number\n private readonly maxMissedAcks: number\n private readonly shouldSendKeepAlive?: () => boolean\n private readonly now: () => number\n\n constructor(\n options: StreamLifecycleOptions,\n private readonly callbacks: StreamLifecycleCallbacks,\n ) {\n this.logger = options.logger.child({component: \"StreamLifecycle\"})\n this.streamId = options.streamId\n this.keepAliveIntervalMs = options.keepAliveIntervalMs\n this.ackTimeoutMs = options.ackTimeoutMs\n this.maxMissedAcks = options.maxMissedAcks\n this.shouldSendKeepAlive = options.shouldSendKeepAlive\n this.now = options.now ?? (() => Date.now())\n this.lastActivityMs = this.now()\n }\n\n setActive(active: boolean): void {\n if (this.disposed || this.active === active) return\n\n this.logger.debug({streamId: this.streamId, active}, \"Updating lifecycle active state\")\n\n this.active = active\n if (active) {\n this.startTimer()\n } else {\n this.stopTimer()\n this.clearPendingAcks()\n this.missedAcks = 0\n }\n }\n\n recordActivity(): void {\n this.lastActivityMs = this.now()\n this.missedAcks = 0\n }\n\n handleAck(ackId: string): void {\n if (this.disposed) return\n\n const ackInfo = this.pendingAcks.get(ackId)\n if (!ackInfo) {\n this.logger.warn({streamId: this.streamId, ackId}, \"Received unknown keep-alive ACK\")\n return\n }\n\n clearTimeout(ackInfo.timeout)\n this.pendingAcks.delete(ackId)\n this.recordActivity()\n\n this.callbacks.onKeepAliveAcked?.(ackId, this.now() - ackInfo.sentAt)\n }\n\n dispose(): void {\n if (this.disposed) return\n\n this.disposed = true\n this.stopTimer()\n this.clearPendingAcks()\n this.logger.debug({streamId: this.streamId}, \"Lifecycle disposed\")\n }\n\n getLastActivityMs(): number {\n return this.lastActivityMs\n }\n\n private startTimer(): void {\n if (this.keepAliveTimer) return\n this.keepAliveTimer = setInterval(() => {\n void this.tick()\n }, this.keepAliveIntervalMs)\n this.logger.debug({streamId: this.streamId}, \"Keep-alive timer started\")\n }\n\n private stopTimer(): void {\n if (this.keepAliveTimer) {\n clearInterval(this.keepAliveTimer)\n this.keepAliveTimer = undefined\n this.logger.debug({streamId: this.streamId}, \"Keep-alive timer stopped\")\n }\n }\n\n private async tick(): Promise<void> {\n if (this.disposed || !this.active) return\n\n if (this.shouldSendKeepAlive && !this.shouldSendKeepAlive()) {\n this.logger.warn(\n {streamId: this.streamId},\n \"Skipping keep-alive send because transport is unavailable\",\n )\n return\n }\n\n const ackId = this.createAckId()\n const sentAt = this.now()\n\n const timeout = setTimeout(() => {\n this.onAckTimeout(ackId, sentAt)\n }, this.ackTimeoutMs)\n\n this.pendingAcks.set(ackId, {sentAt, timeout})\n this.callbacks.onKeepAliveSent?.(ackId)\n\n try {\n await this.callbacks.sendKeepAlive(ackId)\n } catch (error) {\n this.logger.error({streamId: this.streamId, ackId, error}, \"Error sending keep-alive\")\n }\n }\n\n private onAckTimeout(ackId: string, sentAt: number): void {\n if (this.disposed) return\n\n // Race guard: handleAck may have processed the ACK between the timeout\n // being scheduled and this callback running. In that case the ackId is\n // no longer pending — counting it as missed would falsely escalate.\n if (!this.pendingAcks.has(ackId)) return\n\n this.pendingAcks.delete(ackId)\n this.missedAcks += 1\n const ageMs = this.now() - sentAt\n\n this.logger.warn(\n {streamId: this.streamId, ackId, missedAcks: this.missedAcks, ageMs},\n \"Keep-alive ACK timeout\",\n )\n\n this.callbacks.onKeepAliveMissed?.(ackId, ageMs, this.missedAcks)\n\n if (this.missedAcks >= this.maxMissedAcks) {\n this.logger.error(\n {\n streamId: this.streamId,\n missedAcks: this.missedAcks,\n maxMissedAcks: this.maxMissedAcks,\n },\n \"Maximum missed ACKs reached; triggering timeout\",\n )\n\n void this.callbacks.onTimeout()\n }\n }\n\n private clearPendingAcks(): void {\n for (const {timeout} of this.pendingAcks.values()) {\n clearTimeout(timeout)\n }\n this.pendingAcks.clear()\n }\n\n private createAckId(): string {\n return `a${this.now().toString(36).slice(-5)}`\n }\n}\n"]}
|
package/build/types/applet.d.ts
CHANGED
package/build/types/applet.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"applet.js","sourceRoot":"","sources":["../../src/types/applet.ts"],"names":[],"mappings":"AAAA;;GAEG","sourcesContent":["/**\n *
|
|
1
|
+
{"version":3,"file":"applet.js","sourceRoot":"","sources":["../../src/types/applet.ts"],"names":[],"mappings":"AAAA;;GAEG","sourcesContent":["/**\n * App and miniapp types owned by @mentra/engine.\n */\n\nimport type {ReactNode} from \"react\"\n\nimport {HardwareRequirement} from \"./hardware\"\n\nimport type {CompatibilityResult} from \"../utils/hardware/hardware\"\n\n/**\n * App execution model types\n */\nexport type AppletType = \"standard\" | \"background\" | \"system_dashboard\"\n\n/**\n * Permission types that apps can request\n */\nexport type AppPermissionType =\n | \"ALL\"\n | \"MICROPHONE\"\n | \"CAMERA\"\n | \"CALENDAR\"\n | \"LOCATION\"\n | \"BACKGROUND_LOCATION\"\n | \"READ_NOTIFICATIONS\"\n | \"POST_NOTIFICATIONS\"\n\n/**\n * Permission object with type and description\n */\nexport interface AppletPermission {\n type: AppPermissionType\n description?: string\n required?: boolean\n}\n\n/**\n * Minimal app interface for client home screen display\n * Optimized for fast rendering - only essential fields\n *\n * This is the client-facing interface used by mobile apps.\n * Internal cloud services use AppI from models (more fields).\n */\nexport interface AppletInterface {\n packageName: string\n name: string\n webviewUrl: string\n logoUrl: string\n iconComponent?: ReactNode\n type: AppletType\n permissions: AppletPermission[]\n running: boolean\n /**\n * True while this app's UI WebView is mounted in the Compositor overlay.\n * At most one app is foregrounded at a time. Distinct from `running`:\n * a foregrounded app is always running, but a running app may be\n * backgrounded (JSContext alive, WebView torn down). Normalized to a\n * concrete boolean by the apps store's projectApps; literal call sites\n * may omit it.\n */\n foregrounded?: boolean\n healthy: boolean\n hardwareRequirements: HardwareRequirement[]\n /** ISO date string when the app was installed */\n installedDate?: string\n /** ISO date string when the app was last run. Undefined if never run (app is \"new\") */\n lastActiveAt?: string\n}\n\n/**\n * Runtime applet shape used by the engine apps store and OEM hosts.\n *\n * Extends AppletInterface with the host-side fields the manager / OEM tracks\n * outside the manifest: offline routing, hardware compatibility result,\n * loading/hidden/local flags, lifecycle hooks, screenshot, and the\n * dev-miniapp escape hatches (`devUrl` / `isMiniappDev`) that surface a\n * `mentra-miniapp dev` snapshot.\n */\n/**\n * A manifest-declared action a miniapp exposes for other (system) miniapps to\n * invoke via `session.actions`. Populated from `miniapp.json`'s `actions` field.\n * Shape maps 1:1 onto an MCP tool (id→name, description, parameters→inputSchema).\n */\nexport interface DeclaredAction {\n id: string\n description: string\n /** JSON-Schema input descriptor (MCP-compatible subset). */\n parameters?: Record<string, unknown>\n /** JSON-Schema descriptor for the action's structured result. */\n outputSchema?: Record<string, unknown>\n}\n\nexport interface ClientApp extends AppletInterface {\n offline: boolean\n offlineRoute: string\n compatibility?: CompatibilityResult\n loading: boolean\n local: boolean\n hidden: boolean\n onStart?: () => void\n onStop?: () => void\n screenshot?: string\n runtimePermissions?: string[]\n declaredPermissions?: string[]\n version?: string\n needsPcm?: boolean\n needsTranscript?: boolean\n devUrl?: string\n devPort?: number\n isMiniappDev?: boolean\n /** Manifest-declared actions (for session.miniapps.list + invoke gating). */\n actions?: DeclaredAction[]\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"even-realities-g1.d.ts","sourceRoot":"","sources":["../../../src/types/capabilities/even-realities-g1.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;GAEG;AACH,eAAO,MAAM,eAAe,EAAE,
|
|
1
|
+
{"version":3,"file":"even-realities-g1.d.ts","sourceRoot":"","sources":["../../../src/types/capabilities/even-realities-g1.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;GAEG;AACH,eAAO,MAAM,eAAe,EAAE,YAyD7B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"even-realities-g1.js","sourceRoot":"","sources":["../../../src/types/capabilities/even-realities-g1.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAiB;IAC3C,SAAS,EAAE,mBAAmB;IAE9B,kDAAkD;IAClD,SAAS,EAAE,KAAK;IAChB,MAAM,EAAE,IAAI;IAEZ,2DAA2D;IAC3D,UAAU,EAAE,IAAI;IAChB,OAAO,EAAE;QACP,KAAK,EAAE,CAAC;QACR,OAAO,EAAE,KAAK;QACd,KAAK,EAAE,OAAO;QACd,gBAAgB,EAAE,KAAK,EAAE,kEAAkE;QAC3F,UAAU,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE;QACvC,WAAW,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE;QAC/B,YAAY,EAAE,CAAC;QACf,gBAAgB,EAAE,IAAI;QAEtB,4EAA4E;QAC5E,WAAW,EAAE,KAAK;QAClB,gBAAgB,EAAE,CAAC;KACpB;IAED,8DAA8D;IAC9D,aAAa,EAAE,IAAI;IACnB,UAAU,EAAE;QACV,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,KAAK;KACd;IAED,oDAAoD;IACpD,UAAU,EAAE,KAAK;IACjB,OAAO,EAAE,IAAI;IAEb,4FAA4F;IAC5F,MAAM,EAAE,IAAI;IACZ,GAAG,EAAE,IAAI;IAET,iDAAiD;IACjD,SAAS,EAAE,KAAK;IAChB,MAAM,EAAE,IAAI;IAEZ,+CAA+C;IAC/C,QAAQ,EAAE,KAAK;IACf,KAAK,EAAE,IAAI;IAEX,yDAAyD;IACzD,KAAK,EAAE;QACL,kBAAkB,EAAE,KAAK;KAC1B;IAED,+CAA+C;IAC/C,OAAO,EAAE,KAAK;
|
|
1
|
+
{"version":3,"file":"even-realities-g1.js","sourceRoot":"","sources":["../../../src/types/capabilities/even-realities-g1.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAiB;IAC3C,SAAS,EAAE,mBAAmB;IAE9B,kDAAkD;IAClD,SAAS,EAAE,KAAK;IAChB,MAAM,EAAE,IAAI;IAEZ,2DAA2D;IAC3D,UAAU,EAAE,IAAI;IAChB,OAAO,EAAE;QACP,KAAK,EAAE,CAAC;QACR,OAAO,EAAE,KAAK;QACd,KAAK,EAAE,OAAO;QACd,gBAAgB,EAAE,KAAK,EAAE,kEAAkE;QAC3F,UAAU,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE;QACvC,WAAW,EAAE,EAAE,UAAU,EAAE,EAAE,EAAE;QAC/B,YAAY,EAAE,CAAC;QACf,gBAAgB,EAAE,IAAI;QAEtB,4EAA4E;QAC5E,WAAW,EAAE,KAAK;QAClB,gBAAgB,EAAE,CAAC;KACpB;IAED,8DAA8D;IAC9D,aAAa,EAAE,IAAI;IACnB,UAAU,EAAE;QACV,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,KAAK;KACd;IAED,oDAAoD;IACpD,UAAU,EAAE,KAAK;IACjB,OAAO,EAAE,IAAI;IAEb,4FAA4F;IAC5F,MAAM,EAAE,IAAI;IACZ,GAAG,EAAE,IAAI;IAET,iDAAiD;IACjD,SAAS,EAAE,KAAK;IAChB,MAAM,EAAE,IAAI;IAEZ,+CAA+C;IAC/C,QAAQ,EAAE,KAAK;IACf,KAAK,EAAE,IAAI;IAEX,yDAAyD;IACzD,KAAK,EAAE;QACL,kBAAkB,EAAE,KAAK;KAC1B;IAED,+CAA+C;IAC/C,OAAO,EAAE,KAAK;IAEd,4EAA4E;IAC5E,MAAM,EAAE,KAAK;CACd,CAAC","sourcesContent":["/**\n * @fileoverview Even Realities G1 Hardware Capabilities\n *\n * Capability profile for the Even Realities G1 smart glasses model.\n * Defines the hardware and software features available on this device.\n */\n\nimport type { Capabilities } from \"../hardware\";\n\n/**\n * Even Realities G1 capability profile\n */\nexport const evenRealitiesG1: Capabilities = {\n modelName: \"Even Realities G1\",\n\n // Camera capabilities - G1 does not have a camera\n hasCamera: false,\n camera: null,\n\n // Display capabilities - G1 has a green monochrome display\n hasDisplay: true,\n display: {\n count: 2,\n isColor: false,\n color: \"green\",\n canDisplayBitmap: false, // broken in practice — capability stops lying (design doc §3.4.8)\n resolution: { width: 640, height: 200 },\n fieldOfView: { horizontal: 25 },\n maxTextLines: 5,\n adjustBrightness: true,\n\n // Scene display API — no positioned elements; scenes degrade to text walls.\n canPosition: false,\n maxImageElements: 0,\n },\n\n // Microphone capabilities - G1 has one microphone without VAD\n hasMicrophone: true,\n microphone: {\n count: 1,\n hasVAD: false,\n },\n\n // Speaker capabilities - G1 does not have a speaker\n hasSpeaker: false,\n speaker: null,\n\n // IMU capabilities - G1 has IMU for head-up/down detection but raw data not exposed to apps\n hasIMU: true,\n imu: null,\n\n // Button capabilities - G1 does not have buttons\n hasButton: false,\n button: null,\n\n // Light capabilities - G1 does not have lights\n hasLight: false,\n light: null,\n\n // Power capabilities - G1 does not have external battery\n power: {\n hasExternalBattery: false,\n },\n\n // WiFi capabilities - G1 does not support WiFi\n hasWifi: false,\n\n // OTA capabilities - G1 firmware updates are not driven by the ASG OTA flow\n hasOta: false,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"even-realities-g2.d.ts","sourceRoot":"","sources":["../../../src/types/capabilities/even-realities-g2.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;GAEG;AACH,eAAO,MAAM,eAAe,EAAE,
|
|
1
|
+
{"version":3,"file":"even-realities-g2.d.ts","sourceRoot":"","sources":["../../../src/types/capabilities/even-realities-g2.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;GAEG;AACH,eAAO,MAAM,eAAe,EAAE,YA8E7B,CAAC"}
|
|
@@ -68,6 +68,8 @@ export const evenRealitiesG2 = {
|
|
|
68
68
|
},
|
|
69
69
|
// WiFi capabilities - G2 does not support WiFi
|
|
70
70
|
hasWifi: false,
|
|
71
|
+
// OTA capabilities - G2 firmware updates are not driven by the ASG OTA flow
|
|
72
|
+
hasOta: false,
|
|
71
73
|
// Dashboard - G2 renders Even Realities' native dashboard in firmware, so
|
|
72
74
|
// MentraOS does not manage the dashboard or expose dashboard settings for it
|
|
73
75
|
hasNativeDashboard: true,
|