File size: 6,875 Bytes
8a29801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/**

 * MiniappEngine — constructs the MentraJS router singletons (crash controller,

 * UI router, JS router), binds them to the native Crust module + the launcher,

 * wires the dev-server background-respawn signal, and starts the message pump.

 *

 * Engine owns this so a bare OEM's `engine.start()` brings up the local-miniapp

 * engine with no host construction step. Host-only concerns that remain outside

 * engine, such as Mentra-app crashloop telemetry, are attached by the host after

 * this returns via `router.onCrashloop` / `router.onRestartToast`.

 *

 * Idempotent — `ensureMiniappEngine()` returns the same singletons on every call,

 * so it's safe to call from both `engine.start()` and the host bootstrap.

 */

import CrustModule from "@mentra/crust"

import devServerBridge from "./DevServerBridge"
import {fleetEvents} from "./fleet/fleetEvents"
import localMiniappRuntime from "./LocalMiniappRuntime"
import {miniappLauncher} from "./MiniappLauncher"
import {MentraJSCrashController} from "./MentraJSCrashController"
import {MentraJSRouter, type MentraJSCrustBinding} from "./MentraJSRouter"
import {MentraUIRouter} from "./MentraUIRouter"
import {BgTimer} from "../utils/timers"

export interface MiniappEngine {
  router: MentraJSRouter
  uiRouter: MentraUIRouter
  crashController: MentraJSCrashController
}

let engine: MiniappEngine | null = null

function wireDevServerRespawnBackground(router: MentraJSRouter, uiRouter: MentraUIRouter): void {
  devServerBridge.onRespawnBackground(async (packageName) => {
    try {
      // Re-resolve the freshly built bundle (dev: HTTP off the dev server;
      // released: file:// snapshot) via the launcher's shared recipe. Carries
      // the declared permissions + manifest across the respawn — omitting them
      // would respawn the JSContext with no permissions, so SUBSCRIBE gates and
      // per-call dispatch checks would start rejecting after a background
      // hot-reload.
      const resolved = await miniappLauncher.resolveBundle(packageName)
      if (!resolved) {
        console.warn(`MentraJS: respawn-bg could not resolve bundle for ${packageName}`)
        return
      }
      // The rebuilt bundle meets a launch's Mentra App version rule; refused, the running context stays.
      miniappLauncher.assertRunsOnPhone(packageName, resolved)
      // Force a respawn (kill + spawn) rather than launcher.ensureRunning,
      // which is idempotent and would no-op an already-registered context.
      const projectRunning = router.isProjectedRunning(packageName)
      await router.unregister(packageName)
      const ok = await router.spawnAndRegister(packageName, resolved.bgSource, {
        permissions: resolved.declaredPermissions,
        installedManifest: resolved.installedManifest,
        hostTrustedSystem: resolved.hostTrustedSystem,
        projectRunning,
        developmentBuild: resolved.devBuild,
      })
      // A miniapp running as user activity starts again from the new bundle: an automatic launch to Fleet.
      if (projectRunning) {
        const manifest = resolved.installedManifest
        fleetEvents.launchUnlessClaimed({
          packageName,
          ...(manifest?.name ? {miniappName: manifest.name} : {}),
          ...(manifest?.version ? {versionName: manifest.version} : {}),
          start: "automatic",
          outcome: ok ? "started" : "failed",
        })
      }
      if (!ok) {
        console.warn(`MentraJS: respawn-bg failed for ${packageName}`)
        return
      }
      // The respawned JSContext is a fresh MiniappSession with ui.bound false.
      // The mounted WebView won't re-fire mentra.ready() (it's latched), so
      // re-announce it so RPC replies (mentra.request) reach the UI again
      // instead of being dropped while unbound.
      uiRouter.notifyReopen(packageName)
    } catch (e) {
      console.warn(`MentraJS: respawn-bg threw for ${packageName}:`, e)
    }
  })
}

/**

 * Construct (once) and return the MentraJS engine singletons. Starts the router's

 * message pump on first call. Subsequent calls return the same instances.

 */
export function ensureMiniappEngine(): MiniappEngine {
  if (engine) {
    wireDevServerRespawnBackground(engine.router, engine.uiRouter)
    engine.router.start()
    return engine
  }

  // The Crust native module's published TS typing doesn't include the new
  // mentraJs* functions until expo prebuild regenerates it; cast to the binding
  // shapes the routers expect.
  const crust = CrustModule as unknown as MentraJSCrustBinding

  const crashController = new MentraJSCrashController({
    maxRetries: 3,
  })
  const uiRouter = new MentraUIRouter({
    mentraJsDispatchToJs: (packageName: string, envelope: Record<string, unknown>) =>
      (
        CrustModule as unknown as {
          mentraJsDispatchToJs: (p: string, e: Record<string, unknown>) => Promise<void>
        }
      ).mentraJsDispatchToJs(packageName, envelope),
  })
  const router = new MentraJSRouter(localMiniappRuntime, crust)
  router.crashController = crashController
  router.uiRouter = uiRouter
  router.timer = BgTimer

  // Hand the router to the engine MiniappLauncher so headless launch/teardown
  // (apps.ts start/stop, the action broker, the WebView mount path) all spawn
  // through one place.
  miniappLauncher.configure({router})

  // Wire up the dev server's "respawn-bg" signal so a touch under
  // src/background/ kills + re-spawns the JSContext with the latest bundle.
  // The WebView reload path stays separate (devServerBridge.onReload).
  wireDevServerRespawnBackground(router, uiRouter)

  router.start()

  engine = {router, uiRouter, crashController}
  return engine
}

/** Stop the MentraJS message pump and tear down router-managed JSContexts. */
export async function stopMiniappEngine(): Promise<void> {
  const current = engine
  if (!current) return
  // Null the singleton BEFORE the async teardown below: a concurrent
  // ensureMiniappEngine() must construct fresh instead of re-starting (and
  // re-subscribing) the router that is mid-teardown, which would leak a zombie
  // Crust subscription once this function finishes.
  engine = null

  devServerBridge.clearRespawnBackgroundHandler()
  current.router.stop()

  const packages = current.router.registeredPackages()
  await Promise.all(
    packages.map(async (packageName) => {
      try {
        await current.router.unregister(packageName)
      } catch (err) {
        console.warn(`MentraJS: failed to unregister ${packageName} during stop:`, err)
      }
    }),
  )
}

/** Returns the engine singletons if already constructed, else null. */
export function getMiniappEngine(): MiniappEngine | null {
  return engine
}