File size: 10,838 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/**

 * dev facade — `engine.dev`: developer/debug surface over engine-owned state.

 * Backend/cloud URL overrides read+write the engine settings store; the cloud

 * URL setters reconnect the engine-owned cloud client onto the new endpoints;

 *

 * NOTE: the dev-time endpoint *resolution* (Metro-host auto-detect, env defaults)

 * still lives host-side in `@/services/cloudClient` during the migration; this

 * facade manages the explicit overrides + reconnect.

 */
import BluetoothSdk from "@mentra/bluetooth-sdk/internal"
import {isGlassesReady} from "../services/GlassesReadiness"
import {useCloudClientStatusStore} from "../stores/cloudClientStatus"
import {useConnectionStore} from "../stores/connection"
import {useCoreStore} from "../stores/core"
import {useGlassesStore} from "../stores/glasses"
import {useSettingsStore, SETTINGS} from "../stores/settings"
import {cloudClientService} from "../services/CloudClientService"
import {getConfigValues} from "../runtime/bootstrap"
import {decideDevLaunchRoute} from "../utils/devMiniappLaunch"
import {assertDevBuildAllowed, registerDevApp, DEV_APP_PACKAGE_NAME, type DevAppRecord} from "../services/AppRegistry"
import {useAppStatusStore} from "../stores/apps"
import {scopeCloudUrlOverrides} from "../services/cloudEndpointPolicy"

type CloudUrlOverrides = {core?: string; runtime?: string}

/**

 * Reconnect the cloud client onto the current cloud-URL overrides. Explicit

 * partial overrides merge over the boot-resolved config (which carries the

 * host's Metro/env URL resolution); both empty clears the live override.

 */
function applyCloudUrlReconnect(urls: CloudUrlOverrides = currentCloudUrlOverrides()): void {
  const hostResolver = getConfigValues().resolveCloudEndpoints
  if (hostResolver) {
    cloudClientService.reconnect(null)
    return
  }
  const resolved = resolveCloudUrlReconnectTarget(urls)
  if (resolved === undefined) {
    cloudClientService.reconnect(null)
  } else if (resolved) {
    cloudClientService.reconnect(resolved)
  } else {
    console.warn("engine.dev.setCloudUrls: partial cloud override missing boot-resolved sibling endpoint")
  }
}

function currentCloudUrlOverrides(): CloudUrlOverrides {
  const s = useSettingsStore.getState()
  return {
    core: trimSetting(s.getSetting(SETTINGS.cloud_core_url.key)),
    runtime: trimSetting(s.getSetting(SETTINGS.cloud_runtime_url.key)),
  }
}

function resolveCloudUrlReconnectTarget(urls: CloudUrlOverrides): {core: string; runtime: string} | null | undefined {
  const core = trimSetting(urls.core)
  const runtime = trimSetting(urls.runtime)
  if (!core && !runtime) return undefined

  const config = getConfigValues()
  const resolvedCore = core || config.coreUrl?.trim()
  const resolvedRuntime = runtime || config.runtimeUrl?.trim()
  return resolvedCore && resolvedRuntime ? {core: resolvedCore, runtime: resolvedRuntime} : null
}

function trimSetting(value: unknown): string | undefined {
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined
}

function projectRuntimeStatus() {
  const core = useCoreStore.getState()
  const glasses = useGlassesStore.getState()
  const connection = useConnectionStore.getState()
  const cloudClient = useCloudClientStatusStore.getState()
  return {
    searching: core.searching,
    // Copy: the snapshot must not hand callers a mutable reference into the store.
    micRanking: [...core.micRanking],
    currentMic: core.currentMic,
    systemMicUnavailable: core.systemMicUnavailable,
    glassesConnected: glasses.connection.state === "connected",
    glassesFullyBooted: isGlassesReady(glasses.connection),
    bluetoothClassicConnected: glasses.bluetoothClassicConnected,
    coreStatus: connection.status,
    cloudClientStatus: cloudClient.status,
    cloudClientAudioTransport: cloudClient.audioTransport,
  }
}

export type DevRuntimeStatusSnapshot = ReturnType<typeof projectRuntimeStatus>

export const dev = {
  /** The cloud-v2 core/runtime URL overrides. */
  cloudUrls: (): {core?: string; runtime?: string} => {
    const s = useSettingsStore.getState()
    return {core: s.getSetting(SETTINGS.cloud_core_url.key), runtime: s.getSetting(SETTINGS.cloud_runtime_url.key)}
  },
  /** Override the cloud-v2 URLs and reconnect the live client onto them. */
  setCloudUrls: (urls: {core?: string; runtime?: string}) => {
    const config = getConfigValues()
    if (config.resolveCloudEndpoints) {
      const scope = config.cloudDebugScope ?? ""
      const scoped = scopeCloudUrlOverrides(
        {
          scope: useSettingsStore.getState().getSetting(SETTINGS.cloud_url_deployment.key),
          ...currentCloudUrlOverrides(),
        },
        scope,
        urls,
      )
      const values: Record<string, unknown> = {
        [SETTINGS.cloud_url_deployment.key]: scope,
        [SETTINGS.cloud_core_url.key]: scoped.core,
        [SETTINGS.cloud_runtime_url.key]: scoped.runtime,
        [SETTINGS.cached_required_version.key]: "",
      }
      void useSettingsStore
        .getState()
        .setManyLocally(values)
        .then((result) => {
          if (result.is_error()) console.error("engine.dev.setCloudUrls: could not save URLs", result.error)
          else applyCloudUrlReconnect()
        })
      return
    }
    const next = {...currentCloudUrlOverrides(), ...urls}
    const resolved = resolveCloudUrlReconnectTarget(next)
    if (resolved === null) {
      console.warn("engine.dev.setCloudUrls: ignoring partial cloud override without a resolvable sibling endpoint")
      return
    }

    const s = useSettingsStore.getState()
    if (urls.core !== undefined) s.setSetting(SETTINGS.cloud_core_url.key, urls.core)
    if (urls.runtime !== undefined) s.setSetting(SETTINGS.cloud_runtime_url.key, urls.runtime)
    if (resolved === undefined) {
      cloudClientService.reconnect(null)
    } else {
      cloudClientService.reconnect(resolved)
    }
  },

  /** Tear down + rebuild the live cloud client (the dev "reconnect" button). */
  reconnectCloud: (): void => applyCloudUrlReconnect(),

  /** Current native (BLE-process) memory usage in MB — a dev/diagnostics gauge. */
  getMemoryMB: (): number => BluetoothSdk.getMemoryMB(),
  /**

   * Phone-side bluetooth runtime snapshot (the core store read-model: scan/mic/

   * search state) — the diagnostics/data-export surface. Shallow copy.

   */
  bluetoothStatus: (): Record<string, unknown> => {
    const {setCoreInfo: _setCoreInfo, reset: _reset, ...state} = useCoreStore.getState()
    return {...state}
  },

  /**

   * Side-load a miniapp being served from a dev machine (the `mentra dev` / CLI

   * flow) by its URL: probes `<url>/miniapp.json`, and on a reachable manifest

   * registers it under its manifest package so it appears in `engine.miniapps`

   * and can coexist with other dev miniapps. This is the OEM-host equivalent

   * of the first-party

   * developer-URL screen — the registration itself is engine-internal, so a

   * host reaches it here rather than the internal registry. Rendering still

   * flows through the normal display path once the miniapp is started.

   *

   * A dev build is unsigned code under the manifest package name, so it is

   * refused (`ok: false`) while that package is installed with a publisher

   * signature; the user uninstalls it first.

   */
  loadDevMiniapp: async (
    url: string,
    name?: string,
  ): Promise<{ok: true; packageName: string; name: string} | {ok: false; error: string}> => {
    const devUrl = url.trim().replace(/\/+$/, "")
    if (!devUrl) return {ok: false, error: "empty url"}
    const result = await decideDevLaunchRoute("", devUrl)
    if (result.decision !== "live") {
      return {ok: false, error: "dev server unreachable, or no miniapp.json served there"}
    }
    const manifest = result.manifest
    const appName = name ?? manifest.name ?? "Dev Miniapp"
    const packageName = (manifest.packageName as string | undefined) ?? DEV_APP_PACKAGE_NAME
    // Persist the host that answered — not the stale input IP — so home-tile
    // relaunches skip a dead LAN address after mDNS/Metro failover.
    const resolvedUrl = result.resolvedUrl || devUrl
    // The `mentra-miniapp dev` server puts the hot-reload/log sidecar on the
    // user port PLUS ONE — same convention as the first-party developer-URL
    // screen's deriveDevPort.
    let devPort: number | undefined
    try {
      const parsed = Number(new URL(resolvedUrl).port)
      devPort = Number.isFinite(parsed) && parsed > 0 ? parsed + 1 : undefined
    } catch {
      devPort = undefined
    }
    try {
      // Refuse before stopping a running signed install that the dev build may not replace.
      assertDevBuildAllowed(packageName)
      const existing = useAppStatusStore.getState().apps.find((app) => app.packageName === packageName)
      if (existing?.running) await useAppStatusStore.getState().stop(packageName)
      await registerDevApp({
        packageName,
        name: appName,
        iconUrl: manifest.icon ? new URL(manifest.icon, `${resolvedUrl}/`).toString() : `${resolvedUrl}/icon.png`,
        // Persist the host that answered — not the stale input IP.
        devUrl: resolvedUrl,
        devPort,
        type: manifest.type as DevAppRecord["type"],
        permissions: manifest.permissions as DevAppRecord["permissions"],
        hardwareRequirements: manifest.hardwareRequirements as DevAppRecord["hardwareRequirements"],
        actions: manifest.actions as DevAppRecord["actions"],
      })
    } catch (error) {
      return {ok: false, error: error instanceof Error ? error.message : String(error)}
    }
    await useAppStatusStore.getState().refresh()
    return {ok: true, packageName, name: appName}
  },

  /** Current engine runtime status for engine-owned debug surfaces. */
  runtimeStatus: (): DevRuntimeStatusSnapshot => projectRuntimeStatus(),

  /** Subscribe to the projected engine runtime status; returns an unsubscribe. */
  onRuntimeStatus: (cb: (status: DevRuntimeStatusSnapshot) => void): (() => void) => {
    let last = JSON.stringify(projectRuntimeStatus())
    const notify = () => {
      const snap = projectRuntimeStatus()
      const key = JSON.stringify(snap)
      if (key === last) return
      last = key
      cb(snap)
    }
    const unsubscribers = [
      useCoreStore.subscribe(notify),
      useGlassesStore.subscribe(notify),
      useConnectionStore.subscribe(notify),
      useCloudClientStatusStore.subscribe(notify),
    ]
    return () => {
      unsubscribers.forEach((unsubscribe) => unsubscribe())
    }
  },
}