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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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
/**

 * Engine apps store β€” runtime state of installed and local applets.

 *

 * The OEM-facing API: subscribe to the running set, install/uninstall

 * miniapps, start/stop them. The store delegates install plumbing to

 * AppRegistry, and exposes hooks (`useApps`, `useStart`, `useStop`,

 * `useRefresh`, `useStopAll`) that the host UI can read.

 *

 * Source of `apps`:

 *   - Local: appRegistry.getInstalledMiniapps()    (always)

 */

import {useMemo} from "react"
import {AppState} from "react-native"
import {AsyncResult, Result, result as Res} from "typesafe-ts"
import {create} from "zustand"
import type {FleetLaunchFailureReason} from "@mentra/cloud-protocol"

import type {ClientApp} from "../types/applet"
import {DeviceTypes} from "../types/enums"
import {getModelCapabilities} from "../types/hardware"
import {HardwareCompatibility, type CompatibilityResult} from "../utils/hardware/hardware"
import {storage} from "../utils/storage/storage"
import appRegistry, {type UninstallOptions} from "../services/AppRegistry"
import localDisplayManager from "../services/LocalDisplayManager"
import {fleetEvents} from "../services/fleet/fleetEvents"
import {islandNotifications} from "../services/NotificationsEmitter"
import sttModelManager from "../services/STTModelManager"
import {miniappLauncher} from "../services/MiniappLauncher"
import {checkMiniappAge, isMiniappAgeGateOn, miniappRequiredAge} from "../services/miniappAgeGate"
import {miniappRunningRegistry} from "../services/MiniappRunningRegistry"
import {nativeMiniappExecution} from "../services/NativeMiniappExecution"
import {noteMiniappOpened} from "../services/runningUpdatePrompt"
import {isMiniappAvailable} from "../runtime/bootstrap"
import {resolveHiddenStatus} from "./appVisibility"
import {SETTINGS, useSettingsStore} from "./settings"
import BluetoothSdk from "@mentra/bluetooth-sdk"

// ---------------------------------------------------------------------------
// Configuration / hooks
// ---------------------------------------------------------------------------

export interface StartOptions {
  skipNavigation?: boolean
  /** Present the app after launch checks, before bundle loading and runtime startup. */
  onAccepted?: () => void | Promise<void>
  /**

   * Who started the miniapp: `"user"` for a person's own choice (a tap on Home, a pick from the glasses menu),

   * `"automatic"` for everything else. It is the default. Fleet's launch record names it, and only a person's start

   * shows UI: an automatic start that a check refuses (glasses not connected, an update in progress, no speech

   * model) is refused silently.

   */
  trigger?: "user" | "automatic"
}

/** Host seams for a start. The refusal explanations are only for a person's own start. */
export interface AppStoreHooks {
  /** An open was refused because the miniapp is updating; the host explains why. */
  onUpdateBlocked?: (app: ClientApp) => void
  /**

   * A start was blocked because the app is hardware-incompatible. Engine made

   * the decision (and raised the `version_incompatible` notification); the host

   * renders its branded alert here.

   */
  onIncompatibleBlocked?: (app: ClientApp) => void
  /**

   * A start was blocked because the app requires the on-device STT model

   * (declared at registration β€” see AppRegistry.installOfflineApp) and none is

   * installed. Engine decided via its model manager; the host renders the

   * alert / settings navigation here.

   */
  onMissingSpeechModel?: (app: ClientApp) => void
  /** A start was refused because the miniapp's server no longer admits this account; the host explains why. */
  onAccessRevoked?: (app: ClientApp) => void
  /**

   * An open request passed the gates β€” fired on EVERY open, including

   * re-opening an already-running app, so the host's navigation / open

   * animation always plays.

   */
  onOpenRequested?: (app: ClientApp, opts?: StartOptions) => void
}

let hostHooks: AppStoreHooks = {}

/** The running-state change at the end of each start, one at a time (see `start`). */
let startTransitions: Promise<unknown> = Promise.resolve()
/** How many times each package has been stopped, so a start can tell whether a later start stopped it. */
const stopCounts = new Map<string, number>()

function oneStartAtATime<T>(transition: () => Promise<T>): Promise<T> {
  const run = startTransitions.then(transition)
  startTransitions = run.catch(() => {})
  return run
}
const uninstallingPackages = new Set<string>()
const openedByUserListeners = new Set<(packageName: string) => void>()

export function installAppStoreHooks(hooks: AppStoreHooks): void {
  hostHooks = {...hostHooks, ...hooks}
}

/**

 * A person started a miniapp (a `"user"` start) and it now runs. Re-opening one

 * that already runs, and automatic starts (restoring what ran before, an

 * update's restart), are not announced. Returns an unsubscribe.

 */
export function onMiniappOpenedByUser(listener: (packageName: string) => void): () => void {
  openedByUserListeners.add(listener)
  return () => {
    openedByUserListeners.delete(listener)
  }
}

function announceOpenedByUser(packageName: string): void {
  for (const listener of [...openedByUserListeners]) {
    try {
      listener(packageName)
    } catch (error) {
      console.warn("Miniapp opened listener threw", error)
    }
  }
}

// ---------------------------------------------------------------------------
// Store
// ---------------------------------------------------------------------------

interface AppStatusState {
  apps: ClientApp[]
  /** Packages with an update downloading or activating. Opens and uninstall are refused meanwhile. */
  updatingPackages: ReadonlySet<string>
  /**

   * Mark a package as updating until the returned function is called. Throws

   * while it is already updating or being uninstalled.

   */
  beginUpdate: (packageName: string) => () => void
  /** Run `update` with the package marked as updating. */
  runUpdate: <T>(packageName: string, update: () => Promise<T>) => Promise<T>
  /**

   * Source of truth for which app is foregrounded in the Compositor overlay.

   * The per-app `foregrounded` boolean is derived from this in `projectApps`

   * so a refresh can never drop the flag when an app is transiently missing

   * from one of the two refresh passes (local-only then merged). See

   * `projectApps` / `setForeground` / `clearForeground`.

   */
  foregroundedPackage: string | null
  refresh: () => Promise<void>
  /** Resolves true if the app actually started; false if a host gate aborted it or its JS context failed to spawn. */
  start: (app: ClientApp, opts?: StartOptions) => Promise<boolean>
  stop: (packageName: string) => Promise<void>
  setForeground: (packageName: string) => Promise<void>
  clearForeground: () => void
  stopAll: () => AsyncResult<void, Error>
  install: (url: string, opts?: {versionOverride?: string}) => AsyncResult<void, Error>
  uninstall: (packageName: string, version?: string, options?: UninstallOptions) => AsyncResult<void, Error>
  saveScreenshot: (packageName: string, screenshot: string) => Promise<void>
  setHiddenStatus: (packageName: string, status: boolean) => void
  getHiddenStatus: (packageName: string) => boolean
  /** Replace the whole apps array. Hosts use this when their extra source changes. */
  setApps: (apps: ClientApp[]) => void
}

export const DUMMY_APPLET: ClientApp = {
  packageName: "",
  name: "",
  webviewUrl: "",
  logoUrl: "",
  type: "standard",
  permissions: [],
  running: false,
  loading: false,
  healthy: true,
  hardwareRequirements: [],
  offline: true,
  offlineRoute: "",
  local: false,
  hidden: false,
}

export type OrderMap = Record<string, number>
const APP_ORDER_KEY = "foreground_apps_order"

export const saveAppsOrder = (orderMap: OrderMap): Result<void, Error> => {
  return storage.save(APP_ORDER_KEY, orderMap)
}

export const getAppsOrder = (): Result<OrderMap, Error> => {
  return storage.load<OrderMap>(APP_ORDER_KEY)
}

// In-memory cache for hidden flags. `projectApps` reads getHiddenStatus once
// per app per refresh β€” without a cache that was a synchronous JNI hop per
// app per refresh on a hot UI path. Kept consistent with disk by writing
// through in setHiddenStatus. Map of packageName β†’ hidden boolean.
const hiddenStatusCache = new Map<string, boolean>()

const getRawPackageNamePriority = (pkg: string): number => {
  if (pkg.includes("@empty")) {
    return 1000
  }
  return 0
}

export const sortAppsByPackageNamePriority = (a: ClientApp, b: ClientApp): number => {
  const pa = getRawPackageNamePriority(a.packageName)
  const pb = getRawPackageNamePriority(b.packageName)
  if (pa !== pb) {
    return pa - pb
  }
  return a.name.localeCompare(b.name)
}

export const saveLastOpenTime = (packageName: string): void => {
  storage.save(`${packageName}_last_open_time`, Date.now())
}

export const getLastOpenTime = (packageName: string): number => {
  const res = storage.load<number>(`${packageName}_last_open_time`)
  if (res.is_ok()) return res.value
  return 0
}

export const sortAppsByLastOpenTime = async <T extends {packageName: string}>(apps: T[]): Promise<T[]> => {
  const timestamps = apps.map((app) => ({app, time: getLastOpenTime(app.packageName)}))
  return timestamps.sort((a, b) => a.time - b.time).map((entry) => entry.app)
}

const startStopApp = async (app: ClientApp, status: boolean): Promise<void> => {
  if (!status && app.onStop) {
    try {
      app.onStop()
    } catch (e) {
      console.warn(`ISLAND: onStop threw for ${app.packageName}`, e)
    }
  }
  if (status && app.onStart) {
    try {
      app.onStart()
    } catch (e) {
      console.warn(`ISLAND: onStart threw for ${app.packageName}`, e)
    }
  }
}

/**

 * Build the final `apps` array for the store from the installed/offline app

 * source. Pure β€” same inputs -> same outputs.

 */
function projectApps(previousState: AppStatusState, localApps: ClientApp[]): ClientApp[] {
  // Dedupe by packageName, keep first occurrence. A miniapp the host keeps
  // background-only (a Store) never enters the user-facing list.
  const byPackage = new Map<string, ClientApp>()
  for (const app of localApps) {
    if (!isMiniappAvailable(app.packageName)) continue
    if (!byPackage.has(app.packageName)) byPackage.set(app.packageName, app)
  }

  // Index previous snapshot for cheap lookups (was O(NΒ²) via .find()).
  const previousByPackage = new Map<string, ClientApp>()
  for (const oldApp of previousState.apps) {
    previousByPackage.set(oldApp.packageName, oldApp)
  }

  const defaultWearable =
    (useSettingsStore.getState().getSetting(SETTINGS.default_wearable.key) as DeviceTypes | undefined) ||
    DeviceTypes.NONE
  const capabilities = getModelCapabilities(defaultWearable)

  // Single pass: dedupe β†’ screenshot carry-over β†’ compat β†’ hidden, all into
  // fresh objects. The previous in-place mutation re-used object references
  // across refreshes, which broke React.memo / referential-equality
  // memoization downstream (every refresh propagated re-renders even when
  // nothing meaningful changed) AND tripped Reanimated's "tried to modify
  // key of an object already passed to a worklet" warning whenever the home
  // screen's animated app cards held a reference to a previous snapshot's
  // app object that we then mutated.
  //
  // Identity stability: refresh() is event-driven and fires repeatedly (and
  // twice per cycle via the local-only β†’ merged two-pass emit). If we always
  // returned fresh objects, every poll changed the identity of EVERY app β€”
  // which re-rendered the Compositor (via useForegroundApp) mid-slide and made
  // the open/close animation hitch, and churned the home grid / switcher pill.
  // So we build the candidate object, then REUSE the previous reference when
  // nothing meaningful changed. Same pattern as the miniappRunningRegistry
  // projection below. A stable foreground-app reference lets the Compositor's
  // slide run uninterrupted on the UI thread.
  return Array.from(byPackage.values()).map((app) => {
    const next: ClientApp = {
      ...app,
      screenshot: previousByPackage.get(app.packageName)?.screenshot ?? app.screenshot,
      compatibility: HardwareCompatibility.checkCompatibility(app.hardwareRequirements, capabilities),
      // A registry source can force an app off the primary home screen (for
      // example, Miniapp Developer while its home-screen setting is disabled).
      // Compose that gate with the user's persisted home-screen layout instead
      // of replacing it, otherwise a default-false persisted value makes a
      // source-hidden app visible again during projection.
      hidden: resolveHiddenStatus(app.hidden, previousState.getHiddenStatus(app.packageName)),
      // Derive the foreground flag from the store's single source of truth
      // (`foregroundedPackage`), NOT from the previous snapshot. Carrying it over
      // per-app meant a refresh that momentarily omitted an app (e.g. the
      // two-pass local-only β†’ merged emit) would reset its flag to false β€” which
      // raced OfflineAppHost's interceptor guard and made the hosted miniapp fall
      // through to the root router (restart). Deriving here keeps the flag stable
      // across both passes.
      foregrounded: app.packageName === previousState.foregroundedPackage,
      updating: previousState.updatingPackages.has(app.packageName),
    }
    const prev = previousByPackage.get(app.packageName)
    return prev && shallowEqualApp(prev, next) ? prev : next
  })
}

// Cheap equality check used by projectApps to preserve object identity across
// refreshes when nothing meaningful changed. Most keys are compared by
// reference (the source app's nested fields β€” permissions, hardwareRequirements,
// parameters β€” are reference-stable within a refresh). The ONE exception is
// `compatibility`, which projectApps recomputes into a fresh object every call;
// comparing it by reference would always differ and defeat the whole point. We
// compare it structurally instead so identity is only broken when the device's
// actual compatibility verdict changes (e.g. glasses connect/disconnect).
function shallowEqualApp(a: ClientApp, b: ClientApp): boolean {
  const aKeys = Object.keys(a) as (keyof ClientApp)[]
  const bKeys = Object.keys(b) as (keyof ClientApp)[]
  if (aKeys.length !== bKeys.length) return false
  for (const k of aKeys) {
    if (k === "compatibility") {
      if (!compatibilityEqual(a.compatibility, b.compatibility)) return false
      continue
    }
    if (a[k] !== b[k]) return false
  }
  return true
}

function compatibilityEqual(a?: CompatibilityResult, b?: CompatibilityResult): boolean {
  if (a === b) return true
  if (!a || !b) return false
  return (
    a.isCompatible === b.isCompatible &&
    a.missingRequired.length === b.missingRequired.length &&
    a.missingOptional.length === b.missingOptional.length &&
    a.warnings.length === b.warnings.length
  )
}

/** Called by a start once it is past every gate and actually starts the miniapp. */
interface LaunchAttempt {
  begin(): void
}

/**

 * Tells Fleet how each start went, around the launch and without touching it: the result, or the failure it throws,

 * is returned as the launch gave it. Only a start that got past every gate is a launch: `started` when it succeeded,

 * `failed` when the spawn or start itself failed. A refusal (another miniapp is loading, incompatible glasses, a

 * missing speech model, an update in progress, a package that is not available) and re-opening a miniapp that is

 * already running start nothing and are not reported. Nor is opening one of the Mentra App's own screens (a native

 * built-in that declares no `nativeExecution`), which is not a miniapp to Fleet. Fleet's `launch` never throws.

 *

 * From the moment it begins, the start claims the miniapp (`fleetEvents.claimLaunch`): the spawn it causes, which the

 * launcher reports for every other path, and the Compositor's own call to the launcher are this launch, not more.

 */
function reportingLaunches(

  launch: (app: ClientApp, opts: StartOptions | undefined, attempt: LaunchAttempt) => Promise<boolean>,

): (app: ClientApp, opts?: StartOptions) => Promise<boolean> {
  return async (clientApp, opts) => {
    let attempted = false
    let started = false
    const claim: {release?: () => FleetLaunchFailureReason | undefined} = {}
    try {
      started = await launch(clientApp, opts, {
        begin: () => {
          attempted = true
          claim.release ??= fleetEvents.claimLaunch(clientApp.packageName)
        },
      })
      return started
    } finally {
      // The launcher classified any spawn failure it held back for this start; this report carries it.
      const failureReason = claim.release?.()
      if (attempted) {
        fleetEvents.launch({
          packageName: clientApp.packageName,
          miniappName: clientApp.name,
          versionName: clientApp.version,
          start: opts?.trigger ?? "automatic",
          outcome: started ? "started" : "failed",
          ...(!started && failureReason ? {failureReason} : {}),
        })
      }
    }
  }
}

export const useAppStatusStore = create<AppStatusState>((set, get) => ({
  apps: [],
  updatingPackages: new Set(),
  foregroundedPackage: null,

  refresh: async () => {
    const localApps = await appRegistry.getInstalledMiniapps()
    // Update and foreground state may have changed while the registry was read.
    set((state) => {
      // An app the host made unavailable loses foreground ownership. A temporary
      // registry omission keeps it, so ordinary refreshes never reopen the UI.
      const foregroundedPackage =
        state.foregroundedPackage && isMiniappAvailable(state.foregroundedPackage) ? state.foregroundedPackage : null
      return {foregroundedPackage, apps: projectApps({...state, foregroundedPackage}, localApps)}
    })
  },

  beginUpdate: (packageName) => {
    if (get().updatingPackages.has(packageName)) throw new Error(`${packageName} is already updating`)
    if (uninstallingPackages.has(packageName)) throw new Error(`${packageName} is being uninstalled`)
    const setUpdating = (updating: boolean) => {
      set((state) => {
        const updatingPackages = new Set(state.updatingPackages)
        if (updating) updatingPackages.add(packageName)
        else updatingPackages.delete(packageName)
        return {
          updatingPackages,
          apps: state.apps.map((app) => (app.packageName === packageName ? {...app, updating} : app)),
        }
      })
    }
    setUpdating(true)
    let ended = false
    return () => {
      if (ended) return
      ended = true
      setUpdating(false)
    }
  },

  runUpdate: async (packageName, update) => {
    const end = get().beginUpdate(packageName)
    try {
      return await update()
    } finally {
      end()
    }
  },

  start: reportingLaunches(async (clientApp: ClientApp, opts: StartOptions | undefined, attempt: LaunchAttempt) => {
    const state = get()
    const packageName = clientApp.packageName
    // Only a person's own start explains a refusal; anything else is refused silently.
    const byUser = opts?.trigger === "user"
    const explain = byUser ? hostHooks : {}
    if (!isMiniappAvailable(packageName)) return false
    const app = state.apps.find((a) => a.packageName === packageName)
    if (!app) {
      console.error(`ISLAND: app not found for package name: ${packageName}`)
      return false
    }
    if (state.updatingPackages.has(packageName)) {
      explain.onUpdateBlocked?.(app)
      return false
    }
    if (app.local && appRegistry.isMiniappAccessRevoked(packageName)) {
      explain.onAccessRevoked?.(app)
      return false
    }

    // Skip spawning a NEW app while another is mid-launch β€” concurrent spawns
    // race the foreground-only-one teardown. This is checked BEFORE the gates
    // and the onOpenRequested seam (which navigates/foregrounds) so a gated
    // launch doesn't paint a splash it can't back. Re-opening an already-running
    // app is exempt: it has nothing to spawn, so it skips this gate and is
    // allowed to re-navigate/animate below.
    // That exemption is the fix for the "second tap during another app's launch
    // window silently does nothing" bug.
    if (!app.running && state.apps.some((a) => a.loading)) {
      console.log(`ISLAND: skipping start ${packageName} β€” another app is loading`)
      return false
    }

    if (!app.offline && !app.local) {
      console.warn(`ISLAND: cloud-v1 app entries are no longer supported: ${packageName}`)
      return false
    }

    // Hardware-compatibility gate β€” engine decides and blocks; for a person's
    // start the host renders its branded alert via onIncompatibleBlocked
    // (and/or the structured notification below). `!isCompatible` (not `=== false`) keeps the semantics
    // of the host gate this replaces: an unknown verdict blocks, not launches.
    if (!app.compatibility?.isCompatible) {
      islandNotifications.emit({
        kind: "version_incompatible",
        packageName,
        reason: `${app.name ?? packageName} is not compatible with the connected glasses`,
        metadata: {missingRequired: app.compatibility?.missingRequired ?? []},
        timestamp: Date.now(),
      })
      explain.onIncompatibleBlocked?.(app)
      return false
    }

    // Missing-speech-model gate for apps registered with requiresLocalSttModel.
    // Engine decides via its own model manager; the host renders the alert and
    // any settings navigation via onMissingSpeechModel.
    if (appRegistry.requiresLocalSttModel(packageName) && !(await sttModelManager.isModelAvailable())) {
      islandNotifications.emit({
        kind: "missing_speech_model",
        packageName,
        reason: `${app.name ?? packageName} needs an on-device speech model before it can start`,
        timestamp: Date.now(),
      })
      explain.onMissingSpeechModel?.(app)
      return false
    }

    // The age gate, before the screen opens or another miniapp stops, so a refusal changes nothing: the person was
    // asked their age, or told why. Only a gated miniapp waits here. The launch is checked again as its context
    // spawns, for every other way in.
    if (app.local && !app.running && isMiniappAgeGateOn()) {
      const rated = miniappLauncher.installedAgeRating(packageName)
      if (miniappRequiredAge(rated.ageRating) !== null) {
        const verdict = await checkMiniappAge(rated, {interactive: AppState.currentState === "active"})
        if (verdict !== "allowed") return false
      }
    }

    // A model check or the age gate above may have yielded while an update started.
    if (get().updatingPackages.has(packageName)) {
      explain.onUpdateBlocked?.(app)
      return false
    }

    // Host navigation / open-animation seam. Runs on EVERY accepted open β€”
    // including re-opening an already-running app β€” so the animation always
    // plays (BuiltInMiniappCatalog.navigateForApp: overlay apps setForeground
    // for the slide).
    const presentation = opts?.onAccepted?.()
    if (presentation) await presentation
    hostHooks.onOpenRequested?.(app, opts)

    // First-activation mark (moved from the host's old beforeStart β€” engine
    // owns the settings store).
    useSettingsStore.getState().setSetting(SETTINGS.has_ever_activated_app.key, true)

    // If the tapped app is already running, this is a re-open: the nav/foreground
    // above already drove the animation, and there's nothing to spawn. Short-
    // circuit before the spawn pipeline. Another start of it may have finished
    // while this one waited above.
    if (app.running || get().apps.find((a) => a.packageName === packageName)?.running) {
      saveLastOpenTime(packageName)
      return true
    }

    // Past every gate: from here on this is a launch, reported to Fleet as started or failed. A native built-in that
    // declares no execution is the Mentra App's own interface (Settings, Feedback), not a miniapp, and is not reported.
    if (app.local || app.nativeExecution) attempt.begin()

    // Foreground-only-one rule: stop other running standard apps, then mark this one running. Starts that waited
    // above (the age question, a presentation) can get here together, so each does this one at a time, on the
    // state as it is then: the last one in stops the others.
    let stopsWhenMarked = 0
    await oneStartAtATime(async () => {
      if (app.type === "standard") {
        const runningForeground = get().apps.filter(
          (a) => a.running && a.type === "standard" && a.packageName !== packageName,
        )
        for (const r of runningForeground) {
          await get().stop(r.packageName)
        }
      }

      set((s) => ({
        apps: s.apps.map((a) => (a.packageName === packageName ? {...a, running: true, loading: false} : a)),
      }))
      saveLastOpenTime(packageName)
      await startStopApp(app, true)
      stopsWhenMarked = stopCounts.get(packageName) ?? 0
    })
    // A start that came in after this one may have stopped it already: it doesn't come back.
    if ((stopCounts.get(packageName) ?? 0) !== stopsWhenMarked) return false

    // Spawn the background JS context for local miniapps. This used to be a
    // side effect of LocalMiniappView mounting on foreground; pulling it here
    // lets start() actually run the app even when nothing foregrounds it (e.g.
    // a system app launching another miniapp via session.miniapps). Idempotent
    // with the view's own ensureRunning; skipped for native offline built-ins
    // (no JS bundle).
    if (app.local) {
      try {
        await miniappLauncher.ensureRunning(packageName)
      } catch (e) {
        // Spawn / bundle-resolve failed β€” revert the optimistic running flag so
        // the home list and miniapps.list() don't show a "running" app with no
        // JS context, and report failure to the caller (session.miniapps.start).
        console.warn(`ISLAND: launcher.ensureRunning failed for ${packageName}`, e)
        set((s) => ({
          apps: s.apps.map((a) => (a.packageName === packageName ? {...a, running: false, loading: false} : a)),
        }))
        // onStart already persisted running:true to disk (saveLocalAppRunningState)
        // before the spawn; run onStop to undo it so a refresh/reboot doesn't
        // resurrect a "running" app with no JS context.
        await startStopApp(app, false)
        return false
      }
    }

    if (byUser) announceOpenedByUser(packageName)
    return true
  }),

  stop: async (packageName: string) => {
    stopCounts.set(packageName, (stopCounts.get(packageName) ?? 0) + 1)
    const state = get()
    const app = state.apps.find((a) => a.packageName === packageName)
    if (!app) {
      console.error(`ISLAND: app not found for package name: ${packageName}`)
      return
    }

    set((s) => ({
      apps: s.apps.map((a) =>
        a.packageName === packageName ? {...a, running: false, screenshot: undefined, loading: false} : a,
      ),
    }))

    // if there are no apps running, call clearDisplay():
    // read fresh state via get() β€” `state` was captured before the set() above, so it still shows
    // this app as running and would never reach 0 when stopping the last app.
    if (get().apps.filter((a) => a.running).length === 0) {
      BluetoothSdk.clearDisplay()
    }
    await startStopApp(app, false)

    // Tear down the background JS context for local miniapps. No-op for native
    // offline built-ins.
    if (app.local) {
      try {
        await miniappLauncher.stop(packageName)
      } catch (e) {
        console.warn(`ISLAND: launcher.stop failed for ${packageName}`, e)
      }
    }
  },

  setForeground: async (packageName: string) => {
    if (!isMiniappAvailable(packageName)) return
    const app = get().apps.find((a) => a.packageName === packageName)
    if (!app) {
      console.error(`ISLAND: setForeground β€” app not found: ${packageName}`)
      return
    }
    if (get().updatingPackages.has(packageName)) {
      hostHooks.onUpdateBlocked?.(app)
      return
    }
    if (app.local && appRegistry.isMiniappAccessRevoked(packageName)) {
      hostHooks.onAccessRevoked?.(app)
      return
    }

    // Flip the foreground flag synchronously so the Compositor's open
    // animation starts on the same frame as the tap. We do NOT await start()
    // first β€” that gated the flag (and thus the animation) behind the whole
    // JSContext-spawn chain, which was the perceived launch delay. The
    // Compositor/LocalMiniappView already handle the spawn being in-flight
    // (the phase machine), so foregrounding needn't wait for it.
    saveLastOpenTime(packageName)
    set((s) => ({
      foregroundedPackage: packageName,
      apps: s.apps.map((a) => ({...a, foregrounded: a.packageName === packageName})),
    }))
    noteMiniappOpened(packageName)

    // Ensure the JSContext exists. start() is idempotent for an
    // already-running app and enforces the foreground-only-one rule for
    // standard apps. Fire-and-forget after the flag flip so it doesn't block
    // paint.
    // if (!app.running) {
    //   get().start(app)
    // }
  },

  clearForeground: () => {
    set((s) => ({
      foregroundedPackage: null,
      apps: s.apps.some((a) => a.foregrounded)
        ? s.apps.map((a) => (a.foregrounded ? {...a, foregrounded: false} : a))
        : s.apps,
    }))
  },

  stopAll: () => {
    return Res.try_async(async () => {
      const running = get().apps.filter((a) => a.running)
      for (const a of running) {
        await get().stop(a.packageName)
      }
    })
  },

  install: (url, opts) => appRegistry.installFromUrl(url, opts),

  uninstall: (packageName, version, options) => {
    return Res.try_async(async () => {
      if (get().updatingPackages.has(packageName)) throw new Error(`${packageName} is updating; try again shortly`)
      if (uninstallingPackages.has(packageName)) throw new Error(`${packageName} is already being uninstalled`)
      uninstallingPackages.add(packageName)
      try {
        // Only for Fleet's record: a lookup that fails (or throws) never stops the removal.
        const removed =
          version ??
          (await Promise.resolve()
            .then(() => appRegistry.getActiveVersion(packageName))
            .catch(() => undefined))
        const res = await appRegistry.uninstall(packageName, version, options)
        // Fleet (Phase 12): every removal attempt, and how it went. The reason of a failed one is not known here.
        fleetEvents.install({
          packageName,
          operation: "remove",
          source: options?.fleetSource ?? "url",
          ...(removed ? {fromVersion: removed} : {}),
          ...(res.is_error() ? {outcome: "failed" as const, reason: "unknown" as const} : {outcome: "succeeded" as const}),
        })
        if (res.is_error()) throw res.error
        set((s) => ({apps: s.apps.filter((a) => a.packageName !== packageName)}))
      } finally {
        uninstallingPackages.delete(packageName)
      }
    })
  },

  saveScreenshot: async (packageName: string, screenshot: string) => {
    storage.save(`${packageName}_screenshot`, screenshot)
    set((s) => ({
      apps: s.apps.map((a) => (a.packageName === packageName ? {...a, screenshot} : a)),
    }))
  },

  setHiddenStatus: (packageName: string, status: boolean) => {
    hiddenStatusCache.set(packageName, status)
    set((s) => ({
      apps: s.apps.map((a) => (a.packageName === packageName ? {...a, hidden: status} : a)),
    }))
    storage.save(`${packageName}_hidden`, status)
    if (!status) {
      const orderMap = getAppsOrder()
      if (orderMap.is_ok()) {
        delete orderMap.value[packageName]
        saveAppsOrder(orderMap.value)
      }
    }
  },

  getHiddenStatus: (packageName: string): boolean => {
    const cached = hiddenStatusCache.get(packageName)
    if (cached !== undefined) return cached
    const res = storage.load<boolean>(`${packageName}_hidden`)
    const value = res.is_ok() ? res.value : false
    hiddenStatusCache.set(packageName, value)
    return value
  },

  setApps: (apps) =>
    set((state) => ({apps: apps.map((app) => ({...app, updating: state.updatingPackages.has(app.packageName)}))})),
}))

// Project miniappRunningRegistry membership into the store's `running` field
// for local apps so the home tray and switcher reflect actual mount state
// without waiting for the next refresh() cycle.
miniappRunningRegistry.subscribe(() => {
  const running = new Set(miniappRunningRegistry.getAll())
  const state = useAppStatusStore.getState()
  let changed = false
  const updated = state.apps.map((app) => {
    if (!app.local) return app
    const next = running.has(app.packageName)
    if (app.running === next) return app
    changed = true
    return {...app, running: next}
  })
  if (changed) {
    useAppStatusStore.setState({apps: updated})
  }
})

/**

 * The miniapp the user can see: the foregrounded one, while the Mentra App itself is in the foreground. The store

 * keeps a miniapp foregrounded when the app goes to the background or the phone locks; it is not visible then.

 */
export function visibleMiniappPackage(

  state: Pick<AppStatusState, "foregroundedPackage"> = useAppStatusStore.getState(),

): string | null {
  return AppState.currentState === "active" ? state.foregroundedPackage : null
}

// Native built-ins have no JS context, so they never enter miniappRunningRegistry. Which of them is executing is
// derived here, from the store every open, minimize and stop goes through, and from the app state: one that executes
// while open (Gallery) only while it is running and visible, one that executes while running (Notify) whenever it
// runs. A running flag alone is not execution for the first kind: it outlives a minimize, and even a restart.
function executingNativeMiniapps(state: AppStatusState): string[] {
  const visible = visibleMiniappPackage(state)
  const executing: string[] = []
  for (const app of state.apps) {
    if (app.local || !app.running) continue
    if (app.nativeExecution === "running" || (app.nativeExecution === "open" && app.packageName === visible)) {
      executing.push(app.packageName)
    }
  }
  return executing
}
/** The built-ins that execute while they run (Notify) that were executing at the last publish. */
let executingWhileRunning: ReadonlySet<string> = new Set()

/**

 * A built-in that executes while it runs, and starts running without the store's `start`, was restored: its running

 * flag was read back after a process death. That is an automatic launch. A `start` claims, and reports, its own.

 */
function reportRestoredBuiltIns(state: AppStatusState, executing: readonly string[]): void {
  const now = new Set<string>()
  for (const app of state.apps) {
    if (app.local || app.nativeExecution !== "running" || !executing.includes(app.packageName)) continue
    now.add(app.packageName)
    if (executingWhileRunning.has(app.packageName)) continue
    fleetEvents.launchUnlessClaimed({
      packageName: app.packageName,
      miniappName: app.name,
      versionName: app.version,
      start: "automatic",
      outcome: "started",
    })
  }
  executingWhileRunning = now
}

const publishNativeExecution = () => {
  const state = useAppStatusStore.getState()
  const executing = executingNativeMiniapps(state)
  reportRestoredBuiltIns(state, executing)
  nativeMiniappExecution.set(executing)
}
useAppStatusStore.subscribe(publishNativeExecution)
AppState.addEventListener("change", publishNativeExecution)

// The display-manager's core (foreground) slot is DERIVED state: always the
// currently-running standard app, no matter HOW it came to run β€” user tap
// (start()), boot restore (autostartLocalMiniapps β†’ registry projection
// above), crash-respawn, or interop. One reconciler instead of per-path call
// sites, so no launch/stop path can forget to claim or release the slot.
// onCoreAppChange is idempotent, so firing on every store write is free.
useAppStatusStore.subscribe((state) => {
  const core = state.apps.find((a) => a.running && (a.type === "standard" || !a.type))
  localDisplayManager.onCoreAppChange(core?.packageName ?? null)
})

// AppRegistry change events trigger a store refresh.
appRegistry.subscribe(() => {
  void useAppStatusStore.getState().refresh()
})

// Re-evaluate hardware compatibility when the paired/default wearable changes.
useSettingsStore.subscribe(
  (state) => state.getSetting(SETTINGS.default_wearable.key),
  () => {
    void useAppStatusStore.getState().refresh()
  },
)

// ---------------------------------------------------------------------------
// Public hooks
// ---------------------------------------------------------------------------

export const useApps = () => useAppStatusStore((state) => state.apps)

/** `start` for a person's own action (a tap on Home): the launch is reported as a user start unless the caller says otherwise. */
const startForUser: AppStatusState["start"] = (app, opts) =>
  useAppStatusStore.getState().start(app, {...opts, trigger: opts?.trigger ?? "user"})

/** The start function for UI the user acts in. Automatic and system callers use the store's `start` directly. */
export const useStart = () => startForUser
export const useStop = () => useAppStatusStore((state) => state.stop)
export const useSetForeground = () => useAppStatusStore((state) => state.setForeground)
export const useClearForeground = () => useAppStatusStore((state) => state.clearForeground)
export const useRefresh = () => useAppStatusStore((state) => state.refresh)
export const useStopAll = () => useAppStatusStore((state) => state.stopAll)
export const useInstall = () => useAppStatusStore((state) => state.install)
export const useUninstall = () => useAppStatusStore((state) => state.uninstall)

export const useActiveApps = () => {
  const apps = useApps()
  return useMemo(() => apps.filter((app) => app.running), [apps])
}

export const useActiveBackgroundApps = () => {
  const apps = useApps()
  return useMemo(() => apps.filter((app) => app.type === "background" && app.running), [apps])
}

export const useBackgroundApps = () => {
  const apps = useApps()
  return useMemo(
    () => ({
      active: apps.filter((app) => app.type === "background" && app.running),
      inactive: apps.filter((app) => app.type === "background" && !app.running),
    }),
    [apps],
  )
}

export const useActiveForegroundApp = () => {
  const apps = useApps()
  return useMemo(() => apps.find((app) => (app.type === "standard" || !app.type) && app.running) ?? null, [apps])
}

/**

 * The single app currently foregrounded in the Compositor overlay, or null.

 * Driven by setForeground/clearForeground β€” distinct from the "active

 * standard app" (running) selector above.

 */
export const useForegroundApp = () => {
  const apps = useApps()
  return useMemo(() => apps.find((app) => app.foregrounded) ?? null, [apps])
}

export const useActiveBackgroundAppsCount = () => {
  const apps = useApps()
  return useMemo(() => apps.filter((app) => app.type === "background" && app.running).length, [apps])
}

export const useLocalMiniApps = () => {
  const apps = useApps()
  return useMemo(() => apps.filter((app) => app.local), [apps])
}