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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
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
930
931
import {useCallback, useEffect, useMemo, useRef, useState} from "react"

import {ota} from "../facades/ota"
import {
  beginOtaAutoChain,
  clearOtaAutoChainReconnectWait,
  isOtaAutoChainActive,
  OTA_AUTO_CHAIN_RECONNECT_TIMEOUT_MS,
  otaAutoChainFingerprint,
  otaAutoChainReleaseRange,
  otaAutoChainReconnectWaitRemaining,
  stopOtaAutoChain,
  tryAdvanceOtaAutoChain,
  type OtaAutoChainReleaseRange,
} from "../services/OtaAutoChain"
import {
  BES_INSTALL_RESTART_MESSAGE,
  OTA_ERROR_BES_RESTART_REQUIRED_COPY_KEY,
  getOtaErrorMessage,
  otaErrorCopyKey,
  shouldRequireGlassesRebootForBesFailure,
  shouldShowChangeWifiForOtaDownloadFailure,
} from "../services/OtaErrorMapping"
import type {OtaInstallSnapshot} from "../services/OtaInstallCoordinator"
import type {OtaCheckCurrentGlassesResult} from "../services/OtaUpdateCheckService"
import {otaDeviceSessionRevision, subscribeOtaDeviceSession} from "../services/OtaDeviceSession"
import type {ReleaseChangelog} from "../facades/ota"
import {useEngineSnapshot} from "./useEngineSnapshot"

export type MentraLiveOtaFlowPage = "check" | "progress"

export type MentraLiveOtaScreen =
  | "initializing"
  | "checking"
  | "finishing"
  | "update_available"
  | "battery_required"
  | "wifi_required"
  | "up_to_date"
  | "dev_build"
  | "unofficial_client"
  | "check_failed"
  | "update_info_unavailable"
  | "starting"
  | "preparing_hotspot"
  | "updating"
  | "restarting"
  | "verifying"
  | "complete"
  | "failed"
  | "disconnected"

export type MentraLiveOtaErrorCode =
  | "check_failed"
  | "update_info_unavailable"
  | "install_failed"
  | "bes_restart_required"

export type MentraLiveOtaError = {
  code: MentraLiveOtaErrorCode
  /** English copy for hosts without localization. */
  message: string
  /**

   * Copy key for `message` when the failure maps to known copy, so localized hosts can

   * translate it. Null for phone-side watchdog and preflight messages, which are English-only.

   * Optional so host code that builds this type by hand keeps compiling; the hook always sets it.

   */
  copyKey?: string | null
  /**

   * Raw failure code reported by the glasses (`ota_status.error`), for support. Null when the

   * failure originated on the phone. Optional for the same source-compatibility reason.

   */
  glassesCode?: string | null
}

export type MentraLiveOtaTransport = "wifi" | "hotspot"
export type MentraLiveOtaHotspotPhase = "idle" | "downloading" | "starting_hotspot" | "joining_hotspot" | "serving"
export type MentraLiveOtaInstallPhase = "download" | "install"
export type MentraLiveOtaStep = "apk" | "mtk" | "bes"

export type MentraLiveOtaReleaseTransition = {
  /** Current glasses software label. Temporarily backed by the reported ASG app version. */
  fromVersion: string | null
  /** Exact coordinated release identity for the selected OTA pin. */
  toVersion: string
}

export type MentraLiveOtaState = {
  screen: MentraLiveOtaScreen
  connected: boolean
  batteryLevel: number | null
  transport: MentraLiveOtaTransport | null
  updateRequired: boolean
  versionChange: boolean
  versionChangeConverged: boolean
  versionChangePhase: "installing" | "restarting" | "verifying" | null
  wifiConnected: boolean
  wifiStatusKnown: boolean
  hotspotSupported: boolean
  hotspotPhase: MentraLiveOtaHotspotPhase
  hotspotArtifactPercent: number | null
  /**

   * Current phone download context. Index is zero-based; percent applies to this file only.

   * Optional for source compatibility; this hook returns null when no file is active.

   */
  hotspotArtifact?: {kind: MentraLiveOtaStep; index: number; totalCount: number} | null
  phase: MentraLiveOtaInstallPhase | null
  step: MentraLiveOtaStep | null
  currentStep: number | null
  totalSteps: number | null
  progress: number | null
  installingApkOnly: boolean
  firmwareRestarting: boolean
  error: MentraLiveOtaError | null
  canInstall: boolean
  canRetry: boolean
  canFinish: boolean
  canDismiss: boolean
  canDiscard: boolean
  canOpenWifiSetup: boolean
  continueDisabled: boolean
  /** True only after an approved update session reaches a final no-update check. */
  completedUpdate: boolean
  /** Release labels for the offered or just-completed coordinated update. */
  releaseTransition: MentraLiveOtaReleaseTransition | null
  /** Release notes crossed by this update, newest first. Populated on completion. */
  changelogs: ReleaseChangelog[]
  /** Sideloaded glasses client package, set only on the `unofficial_client` screen. */
  glassesPackageName: string | null
}

export type UseMentraLiveOtaOptions = {
  /** Entry page. `progress` exists for interrupted-session recovery. */
  initialPage?: MentraLiveOtaFlowPage
  /** Start Engine's OTA-only projections. Full Engine hosts should pass false. */
  initializeRuntime?: boolean
  /** Called after the final check or when an optional update is dismissed. */
  onFinished?: () => void
  /** Host-owned Wi-Fi setup for glasses without hotspot OTA support. */
  onOpenWifiSetup?: () => void
  /** Lets a host coordinate its connection overlay with OTA firmware restarts. */
  onFirmwareRestartingChange?: (restarting: boolean, progressActive: boolean) => void
}

export type MentraLiveOtaController = {
  state: MentraLiveOtaState
  check: () => void
  retryCheck: () => void
  install: () => void
  retryInstall: () => void
  finish: () => void
  discard: () => void
  openWifiSetup: () => void
}

type CheckState = "checking" | "update_available" | "no_update" | "dev_build" | "unofficial_client" | "error"

const AUTO_CHAIN_NETWORK_RETRY_DELAY_MS = 5000
const AUTO_CHAIN_COMPLETE_DELAY_MS = 750
export const MINIMUM_OTA_BATTERY_LEVEL = 25

function releaseRangeTargetVersion(result: OtaCheckCurrentGlassesResult): string | null {
  return result.releaseVersion ?? result.updateInfo?.versionName ?? result.latestVersionInfo?.versionName ?? null
}

function currentReleaseVersion(appVersion: string | null): string | null {
  const version = appVersion?.trim()
  return version || null
}

function releaseTransitionFromRange(range: OtaAutoChainReleaseRange | null): MentraLiveOtaReleaseTransition | null {
  if (!range?.releaseVersion) return null
  return {fromVersion: range.fromVersion, toVersion: range.releaseVersion}
}

function releaseChangelogsForActiveChain(): ReleaseChangelog[] {
  const range = otaAutoChainReleaseRange()
  if (!range?.toVersion) return []
  try {
    return ota.getReleaseChangelogs(range.fromVersion, range.toVersion)
  } catch {
    try {
      return ota.getReleaseChangelogs(null, range.toVersion)
    } catch {
      return []
    }
  }
}

function installProgress(snapshot: OtaInstallSnapshot): number | null {
  if (snapshot.displayState !== "updating") return null
  const {otaStatus} = snapshot
  const isDownload = otaStatus?.phase === "download"
  const totalSteps = otaStatus?.totalSteps ?? 1
  const rawPercent = isDownload
    ? (otaStatus?.stepPercent ?? 0)
    : totalSteps >= 2
      ? (otaStatus?.overallPercent ?? 0)
      : (otaStatus?.stepPercent ?? 0)
  return Math.min(Math.max(rawPercent, snapshot.mtkInstallStallSimulatedPercent ?? 0, 0), 100)
}

function progressScreen(snapshot: OtaInstallSnapshot): MentraLiveOtaScreen {
  if (snapshot.versionChangePhase === "restarting") return "restarting"
  if (snapshot.versionChangePhase === "verifying") return "verifying"
  switch (snapshot.displayState) {
    case "starting":
      return snapshot.hotspotPhase === "idle" || snapshot.hotspotPhase === "serving" ? "starting" : "preparing_hotspot"
    case "updating":
      return "updating"
    case "restarting":
      return "restarting"
    case "complete":
      return "complete"
    case "failed":
      return "failed"
    default:
      return "disconnected"
  }
}

/**

 * Headless Mentra Live OTA flow. Engine owns checking, hotspot staging,

 * APK/MTK/BES sequencing, restart recovery, retries, and verification; the host

 * renders semantic state and invokes these idempotent actions.

 */
export function useMentraLiveOta(options: UseMentraLiveOtaOptions = {}): MentraLiveOtaController {
  const {
    initialPage = "check",
    initializeRuntime = true,
    onFinished,
    onFirmwareRestartingChange,
    onOpenWifiSetup,
  } = options
  const otaSnapshot = useEngineSnapshot(ota.snapshot, ota.onSnapshot)
  const deviceRevision = useEngineSnapshot(otaDeviceSessionRevision, subscribeOtaDeviceSession)
  const installSnapshot = useEngineSnapshot(ota.installSession.snapshot, ota.installSession.onSnapshot)
  const [page, setPage] = useState<MentraLiveOtaFlowPage>(initialPage)
  const [runtimeReady, setRuntimeReady] = useState(!initializeRuntime)
  const [checkState, setCheckState] = useState<CheckState>("checking")
  const [isUpdateRequired, setIsUpdateRequired] = useState(true)
  const [isVersionChange, setIsVersionChange] = useState(false)
  const [errorKind, setErrorKind] = useState<"network" | "pin_unavailable" | "version_info">("network")
  const [unofficialClientPackage, setUnofficialClientPackage] = useState<string | null>(null)
  const [updateFingerprint, setUpdateFingerprint] = useState<string | null>(null)
  const [offeredReleaseTransition, setOfferedReleaseTransition] = useState<MentraLiveOtaReleaseTransition | null>(null)
  const [completedReleaseTransition, setCompletedReleaseTransition] = useState<MentraLiveOtaReleaseTransition | null>(
    null,
  )
  const [completedUpdate, setCompletedUpdate] = useState(false)
  const [completedChangelogs, setCompletedChangelogs] = useState<ReleaseChangelog[]>([])
  const [batteryBlocked, setBatteryBlocked] = useState(false)
  const [checkGeneration, setCheckGeneration] = useState(0)
  const mountedRef = useRef(false)
  const performCheckGenerationRef = useRef(0)
  const activeCheckKeyRef = useRef<string | null>(null)
  const checkStartedRef = useRef(false)
  const checkCompletedRef = useRef(false)
  const selectedCheckResultRef = useRef<OtaCheckCurrentGlassesResult | null>(null)
  const selectedCheckDeviceRef = useRef(deviceRevision)
  const previousDeviceRef = useRef(deviceRevision)
  const autoChainAdvancedRef = useRef(false)
  const installActionPendingRef = useRef(false)
  const onFinishedRef = useRef(onFinished)
  const onOpenWifiSetupRef = useRef(onOpenWifiSetup)
  const onFirmwareRestartingChangeRef = useRef(onFirmwareRestartingChange)
  onFinishedRef.current = onFinished
  onOpenWifiSetupRef.current = onOpenWifiSetup
  onFirmwareRestartingChangeRef.current = onFirmwareRestartingChange

  useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  }, [])

  useEffect(() => {
    if (!initializeRuntime) {
      setRuntimeReady(true)
      return
    }
    let cancelled = false
    setRuntimeReady(false)
    void ota.initialize().finally(() => {
      if (!cancelled) setRuntimeReady(true)
    })
    return () => {
      cancelled = true
    }
  }, [initializeRuntime])

  const returnToCheck = useCallback(() => {
    installActionPendingRef.current = false
    autoChainAdvancedRef.current = false
    setCheckState("checking")
    setPage("check")
    setCheckGeneration((generation) => generation + 1)
  }, [])

  useEffect(() => {
    if (previousDeviceRef.current === deviceRevision) return
    previousDeviceRef.current = deviceRevision
    performCheckGenerationRef.current += 1
    selectedCheckResultRef.current = null
    setUpdateFingerprint(null)
    setOfferedReleaseTransition(null)
    setCompletedReleaseTransition(null)
    setCompletedUpdate(false)
    setCompletedChangelogs([])
    setBatteryBlocked(false)
    setIsVersionChange(false)
    returnToCheck()
  }, [deviceRevision, returnToCheck])

  const navigateToProgress = useCallback(() => {
    installActionPendingRef.current = true
    ota.clearProgress()
    setPage("progress")
  }, [])

  const continueApprovedChain = useCallback(
    (result: OtaCheckCurrentGlassesResult): boolean => {
      if (deviceRevision !== otaDeviceSessionRevision() || selectedCheckDeviceRef.current !== deviceRevision)
        return false
      if (installActionPendingRef.current || !isOtaAutoChainActive() || !result.updateInfo) return false
      const snapshot = ota.snapshot()
      if (snapshot.hotspotOtaVersion !== 1 && (!snapshot.wifiStatusKnown || !snapshot.wifiConnected)) return false

      const admission = tryAdvanceOtaAutoChain(
        otaAutoChainFingerprint(result),
        result.updateInfo.isDowngrade === true,
        releaseRangeTargetVersion(result),
        result.releaseVersion,
      )
      if (!admission.advance) return false

      checkCompletedRef.current = true
      ota.installSession.prepare(result)
      navigateToProgress()
      return true
    },
    [deviceRevision, navigateToProgress],
  )

  useEffect(() => {
    if (!runtimeReady || page !== "check") {
      if (checkStartedRef.current && !checkCompletedRef.current) {
        performCheckGenerationRef.current += 1
        checkStartedRef.current = false
      }
      return
    }
    const MIN_DISPLAY_TIME_MS = 1100
    const MAX_WAIT_FOR_VERSION_INFO_MS = 10_000
    const checkKey = `${deviceRevision}:${checkGeneration}`
    if (activeCheckKeyRef.current !== checkKey) {
      performCheckGenerationRef.current += 1
      activeCheckKeyRef.current = checkKey
      checkStartedRef.current = false
      checkCompletedRef.current = false
      selectedCheckResultRef.current = null
      installActionPendingRef.current = false
      setCheckState("checking")
    }

    let reconnectTimeout: ReturnType<typeof setTimeout> | null = null

    const performCheck = async () => {
      if (checkCompletedRef.current) return
      if (isOtaAutoChainActive() && !otaSnapshot.ready) {
        if (checkStartedRef.current) {
          performCheckGenerationRef.current += 1
          checkStartedRef.current = false
        }
        const remainingMs = otaAutoChainReconnectWaitRemaining()
        if (remainingMs === null) return
        const reconnectGeneration = performCheckGenerationRef.current
        reconnectTimeout = setTimeout(() => {
          if (
            !mountedRef.current ||
            deviceRevision !== otaDeviceSessionRevision() ||
            reconnectGeneration !== performCheckGenerationRef.current ||
            ota.snapshot().ready
          )
            return
          stopOtaAutoChain()
          checkCompletedRef.current = true
          setCheckState("error")
        }, remainingMs)
        return
      }
      if (!otaSnapshot.connected) {
        if (checkStartedRef.current) {
          performCheckGenerationRef.current += 1
          checkStartedRef.current = false
          stopOtaAutoChain()
          checkCompletedRef.current = true
          setCheckState("error")
          return
        }
        checkCompletedRef.current = true
        onFinishedRef.current?.()
        return
      }
      if (checkStartedRef.current) return

      clearOtaAutoChainReconnectWait()
      checkStartedRef.current = true
      const myGeneration = ++performCheckGenerationRef.current
      const isCurrentCheck = () =>
        mountedRef.current &&
        myGeneration === performCheckGenerationRef.current &&
        deviceRevision === otaDeviceSessionRevision()
      const startTime = Date.now()
      try {
        const checkOptions = {
          waitForBuildNumberMs: MAX_WAIT_FOR_VERSION_INFO_MS,
          waitForBesVersionMs: 5000,
          waitForMtkVersionMs: 2000,
          waitForLegacyMigrationMs: isOtaAutoChainActive() ? OTA_AUTO_CHAIN_RECONNECT_TIMEOUT_MS : 0,
          refreshVersionInfo: true,
          fixClockBeforeCheck: false,
        }
        let result = await ota.checkForUpdates(checkOptions)
        if (!isCurrentCheck()) return
        if (!result.hasCheckCompleted && result.checkFailureReason === "network" && isOtaAutoChainActive()) {
          await new Promise((resolve) => setTimeout(resolve, AUTO_CHAIN_NETWORK_RETRY_DELAY_MS))
          if (!isCurrentCheck()) return
          result = await ota.checkForUpdates(checkOptions)
        }
        if (!isCurrentCheck()) return
        selectedCheckResultRef.current = result
        selectedCheckDeviceRef.current = deviceRevision
        await new Promise((resolve) => setTimeout(resolve, Math.max(0, MIN_DISPLAY_TIME_MS - (Date.now() - startTime))))
        if (!isCurrentCheck()) return

        if (result.skippedReason === "disconnected") {
          stopOtaAutoChain()
          checkCompletedRef.current = true
          setCheckState("error")
          return
        }
        if (result.skippedReason === "missing_build") {
          checkCompletedRef.current = true
          if (isOtaAutoChainActive()) {
            stopOtaAutoChain()
            setCheckState("error")
          } else {
            onFinishedRef.current?.()
          }
          return
        }
        if (result.skippedReason === "dev_build") {
          stopOtaAutoChain()
          checkCompletedRef.current = true
          ota.clearUpdateAvailable()
          setCheckState("dev_build")
          return
        }
        if (result.skippedReason === "unofficial_client") {
          stopOtaAutoChain()
          checkCompletedRef.current = true
          ota.clearUpdateAvailable()
          setUnofficialClientPackage(result.packageName ?? null)
          setCheckState("unofficial_client")
          return
        }
        if (!result.hasCheckCompleted) {
          // A failed device verification is not a completed chain. Retain its
          // approval so Retry still verifies the release pin after legacy rescue.
          if (result.checkFailureReason !== "version_info") stopOtaAutoChain()
          checkCompletedRef.current = true
          setErrorKind(result.checkFailureReason ?? "network")
          setCheckState("error")
          return
        }
        if (result.updateAvailable && result.updateInfo) {
          setIsUpdateRequired(result.isRequired)
          setIsVersionChange(result.updateInfo.isDowngrade === true)
          const fingerprint = otaAutoChainFingerprint(result)
          setUpdateFingerprint(fingerprint)
          if (!isOtaAutoChainActive()) {
            const fromVersion = currentReleaseVersion(ota.snapshot().appVersion)
            setOfferedReleaseTransition(result.releaseVersion ? {fromVersion, toVersion: result.releaseVersion} : null)
          }
          if (isOtaAutoChainActive() && !ota.snapshot().wifiStatusKnown && ota.snapshot().hotspotOtaVersion !== 1) {
            checkCompletedRef.current = true
            return
          }
          if (continueApprovedChain(result)) return
          checkCompletedRef.current = true
          setCheckState("update_available")
          return
        }
        const completedApprovedSession = isOtaAutoChainActive()
        if (completedApprovedSession) {
          setCompletedChangelogs(releaseChangelogsForActiveChain())
          setCompletedReleaseTransition(releaseTransitionFromRange(otaAutoChainReleaseRange()))
        }
        setCompletedUpdate(completedApprovedSession)
        stopOtaAutoChain()
        checkCompletedRef.current = true
        ota.clearUpdateAvailable()
        setCheckState("no_update")
      } catch (error) {
        console.error("OTA check failed:", error)
        await new Promise((resolve) => setTimeout(resolve, Math.max(0, MIN_DISPLAY_TIME_MS - (Date.now() - startTime))))
        if (!isCurrentCheck()) return
        stopOtaAutoChain()
        checkCompletedRef.current = true
        setErrorKind("network")
        setCheckState("error")
      }
    }

    void performCheck()
    return () => {
      if (reconnectTimeout) clearTimeout(reconnectTimeout)
    }
  }, [
    checkGeneration,
    deviceRevision,
    continueApprovedChain,
    otaSnapshot.connected,
    otaSnapshot.ready,
    otaSnapshot.wifiStatusKnown,
    page,
    runtimeReady,
  ])

  useEffect(() => {
    if (
      !runtimeReady ||
      page !== "check" ||
      (checkState !== "checking" && checkState !== "update_available") ||
      (!otaSnapshot.wifiStatusKnown && otaSnapshot.hotspotOtaVersion !== 1) ||
      !isOtaAutoChainActive()
    ) {
      return
    }
    const result = selectedCheckResultRef.current
    if (!result?.updateAvailable || !result.updateInfo) return
    if (!otaSnapshot.wifiConnected && otaSnapshot.hotspotOtaVersion !== 1) {
      setCheckState("update_available")
      return
    }
    continueApprovedChain(result)
  }, [
    checkState,
    continueApprovedChain,
    otaSnapshot.hotspotOtaVersion,
    otaSnapshot.wifiConnected,
    otaSnapshot.wifiStatusKnown,
    page,
    runtimeReady,
  ])

  useEffect(() => {
    if (!runtimeReady || page !== "progress") return
    ota.installSession.attach()
    return () => ota.installSession.detach()
  }, [page, runtimeReady])

  const firmwareRestarting =
    page === "progress" &&
    ((!installSnapshot.connected && installSnapshot.displayState === "restarting") ||
      installSnapshot.versionChangePhase === "restarting")

  useEffect(() => {
    if (page !== "progress") return
    onFirmwareRestartingChangeRef.current?.(firmwareRestarting, true)
  }, [firmwareRestarting, page])

  useEffect(() => {
    if (page !== "progress") return
    return () => {
      onFirmwareRestartingChangeRef.current?.(false, false)
    }
  }, [page])

  useEffect(() => {
    if (
      page !== "progress" ||
      installSnapshot.displayState !== "complete" ||
      !installSnapshot.connected ||
      !isOtaAutoChainActive() ||
      autoChainAdvancedRef.current
    ) {
      return
    }
    const timeout = setTimeout(async () => {
      if (deviceRevision !== otaDeviceSessionRevision() || !isOtaAutoChainActive()) return
      autoChainAdvancedRef.current = true
      await ota.installSession.finish()
      if (deviceRevision !== otaDeviceSessionRevision()) return
      returnToCheck()
    }, AUTO_CHAIN_COMPLETE_DELAY_MS)
    return () => clearTimeout(timeout)
  }, [deviceRevision, installSnapshot.connected, installSnapshot.displayState, page, returnToCheck])

  const check = useCallback(() => {
    setBatteryBlocked(false)
    setOfferedReleaseTransition(null)
    setCompletedReleaseTransition(null)
    setCompletedUpdate(false)
    setCompletedChangelogs([])
    setPage("check")
    setCheckState("checking")
    setCheckGeneration((generation) => generation + 1)
  }, [])

  const install = useCallback(() => {
    if (installActionPendingRef.current || page !== "check") return
    if (deviceRevision !== otaDeviceSessionRevision() || selectedCheckDeviceRef.current !== deviceRevision) return
    const result = selectedCheckResultRef.current
    if (!result) {
      setErrorKind("network")
      setCheckState("error")
      return
    }
    const snapshot = ota.snapshot()
    if (snapshot.batteryLevel !== null && snapshot.batteryLevel < MINIMUM_OTA_BATTERY_LEVEL) {
      setBatteryBlocked(true)
      return
    }
    if (!snapshot.wifiStatusKnown && snapshot.hotspotOtaVersion !== 1) {
      check()
      return
    }
    if (!snapshot.wifiConnected && snapshot.hotspotOtaVersion !== 1) {
      onOpenWifiSetupRef.current?.()
      return
    }
    ota.installSession.prepare(result)
    setBatteryBlocked(false)
    setCompletedUpdate(false)
    setCompletedChangelogs([])
    if (updateFingerprint) {
      const fromVersion = offeredReleaseTransition
        ? offeredReleaseTransition.fromVersion
        : currentReleaseVersion(snapshot.appVersion)
      beginOtaAutoChain(updateFingerprint, isVersionChange, {
        fromVersion,
        toVersion: releaseRangeTargetVersion(result),
        releaseVersion: result.releaseVersion,
      })
    }
    navigateToProgress()
  }, [check, deviceRevision, isVersionChange, navigateToProgress, offeredReleaseTransition, page, updateFingerprint])

  useEffect(() => {
    if (
      batteryBlocked &&
      (otaSnapshot.batteryLevel === null || otaSnapshot.batteryLevel >= MINIMUM_OTA_BATTERY_LEVEL)
    ) {
      setBatteryBlocked(false)
    }
  }, [batteryBlocked, otaSnapshot.batteryLevel])

  const retryInstall = useCallback(() => {
    if (deviceRevision !== otaDeviceSessionRevision() || page !== "progress") return
    onFirmwareRestartingChangeRef.current?.(false, true)
    ota.installSession.retry()
  }, [deviceRevision, page])

  const finish = useCallback(async () => {
    if (deviceRevision !== otaDeviceSessionRevision()) return
    if (page === "check") {
      stopOtaAutoChain()
      onFinishedRef.current?.()
      return
    }
    const restartStillInProgress =
      installSnapshot.displayState === "restarting" ||
      installSnapshot.versionChangePhase === "restarting" ||
      installSnapshot.versionChangePhase === "verifying"
    if (restartStillInProgress) return
    const requiresGlassesReboot = shouldRequireGlassesRebootForBesFailure(
      installSnapshot.otaStatus,
      installSnapshot.otaProgress,
      installSnapshot.errorMsg,
    )
    if (requiresGlassesReboot) stopOtaAutoChain()
    await ota.installSession.finish()
    if (deviceRevision !== otaDeviceSessionRevision()) return
    returnToCheck()
  }, [deviceRevision, installSnapshot, page, returnToCheck])

  const discard = useCallback(async () => {
    if (deviceRevision !== otaDeviceSessionRevision()) return
    if (page !== "progress") return
    stopOtaAutoChain()
    await ota.installSession.discard()
    if (deviceRevision !== otaDeviceSessionRevision()) return
    returnToCheck()
  }, [deviceRevision, page, returnToCheck])

  const openWifiSetup = useCallback(() => {
    if (page === "progress") stopOtaAutoChain()
    onOpenWifiSetupRef.current?.()
  }, [page])

  const state = useMemo<MentraLiveOtaState>(() => {
    const hotspotSupported = otaSnapshot.hotspotOtaVersion === 1
    const canInstall = hotspotSupported || (otaSnapshot.wifiStatusKnown && otaSnapshot.wifiConnected)
    const autoChainActive = isOtaAutoChainActive()
    if (!runtimeReady) {
      return {
        screen: "initializing",
        connected: otaSnapshot.connected,
        batteryLevel: otaSnapshot.batteryLevel,
        transport: null,
        updateRequired: isUpdateRequired,
        versionChange: isVersionChange,
        versionChangeConverged: false,
        versionChangePhase: null,
        wifiConnected: otaSnapshot.wifiConnected,
        wifiStatusKnown: otaSnapshot.wifiStatusKnown,
        hotspotSupported,
        hotspotPhase: "idle",
        hotspotArtifactPercent: null,
        hotspotArtifact: null,
        phase: null,
        step: null,
        currentStep: null,
        totalSteps: null,
        progress: null,
        installingApkOnly: false,
        firmwareRestarting: false,
        error: null,
        canInstall: false,
        canRetry: false,
        canFinish: false,
        canDismiss: false,
        canDiscard: false,
        canOpenWifiSetup: false,
        continueDisabled: false,
        completedUpdate: false,
        releaseTransition: null,
        changelogs: [],
        glassesPackageName: null,
      }
    }

    if (page === "check") {
      const wifiRequired = otaSnapshot.wifiStatusKnown && !otaSnapshot.wifiConnected && !hotspotSupported
      let screen: MentraLiveOtaScreen
      if (checkState === "checking") screen = autoChainActive ? "finishing" : "checking"
      else if (checkState === "update_available") {
        screen = wifiRequired ? "wifi_required" : batteryBlocked ? "battery_required" : "update_available"
      } else if (checkState === "no_update") screen = "up_to_date"
      else if (checkState === "dev_build") screen = "dev_build"
      else if (checkState === "unofficial_client") screen = "unofficial_client"
      else screen = errorKind === "pin_unavailable" ? "update_info_unavailable" : "check_failed"

      let error: MentraLiveOtaError | null = null
      if (screen === "check_failed") {
        error = {
          code: "check_failed",
          message:
            errorKind === "version_info"
              ? "Couldn't read the glasses software versions. Keep the glasses connected and try again."
              : "Couldn't check for updates. Please check your connection and try again.",
          copyKey: errorKind === "version_info" ? "ota:versionInfoFailedMessage" : "ota:checkFailedMessage",
          glassesCode: null,
        }
      } else if (screen === "update_info_unavailable") {
        error = {
          code: "update_info_unavailable",
          message: "Update information for this app version is unavailable.",
          copyKey: "ota:updateInfoUnavailableMessage",
          glassesCode: null,
        }
      }
      return {
        screen,
        connected: otaSnapshot.connected,
        batteryLevel: otaSnapshot.batteryLevel,
        transport: hotspotSupported ? "hotspot" : otaSnapshot.wifiConnected ? "wifi" : null,
        updateRequired: isUpdateRequired,
        versionChange: isVersionChange,
        versionChangeConverged: false,
        versionChangePhase: null,
        wifiConnected: otaSnapshot.wifiConnected,
        wifiStatusKnown: otaSnapshot.wifiStatusKnown,
        hotspotSupported,
        hotspotPhase: "idle",
        hotspotArtifactPercent: null,
        hotspotArtifact: null,
        phase: null,
        step: null,
        currentStep: null,
        totalSteps: null,
        progress: null,
        installingApkOnly: false,
        firmwareRestarting: false,
        error,
        canInstall: screen === "update_available" && canInstall,
        canRetry: screen === "check_failed",
        canFinish:
          screen === "up_to_date" ||
          screen === "dev_build" ||
          screen === "unofficial_client" ||
          screen === "update_info_unavailable",
        canDismiss:
          (screen === "update_available" || screen === "wifi_required" || screen === "battery_required") &&
          !isUpdateRequired &&
          !autoChainActive,
        canDiscard: false,
        canOpenWifiSetup: screen === "wifi_required",
        continueDisabled: false,
        completedUpdate: screen === "up_to_date" && completedUpdate,
        releaseTransition:
          screen === "update_available" || screen === "wifi_required"
            ? autoChainActive
              ? releaseTransitionFromRange(otaAutoChainReleaseRange())
              : offeredReleaseTransition
            : screen === "up_to_date"
              ? completedReleaseTransition
              : null,
        changelogs: screen === "up_to_date" ? completedChangelogs : [],
        glassesPackageName: screen === "unofficial_client" ? unofficialClientPackage : null,
      }
    }

    const requiresGlassesReboot = shouldRequireGlassesRebootForBesFailure(
      installSnapshot.otaStatus,
      installSnapshot.otaProgress,
      installSnapshot.errorMsg,
    )
    const showChangeWifi = shouldShowChangeWifiForOtaDownloadFailure(
      installSnapshot.otaStatus,
      installSnapshot.otaProgress,
      installSnapshot.errorMsg,
    )
    // The raw code the glasses attached to their failure report, kept for support even when
    // phone-side copy outranks it. Only a failed ota_status carries a current code.
    const glassesCode = installSnapshot.otaStatus?.status === "failed" ? installSnapshot.otaStatus.error || null : null
    // Precedence mirrors the legacy screen: the BES restart instruction, then a phone-side
    // watchdog/preflight message (translated when a copy key is available), then the glasses code mapped to
    // copy (unknown codes get the generic glasses-error copy rather than the raw code).
    let displayedError: string
    let copyKey: string | null
    if (requiresGlassesReboot) {
      displayedError = BES_INSTALL_RESTART_MESSAGE
      copyKey = OTA_ERROR_BES_RESTART_REQUIRED_COPY_KEY
    } else if (installSnapshot.errorMsg) {
      displayedError = installSnapshot.errorMsg
      copyKey = installSnapshot.errorCopyKey ?? null
    } else {
      displayedError = getOtaErrorMessage(glassesCode)
      copyKey = otaErrorCopyKey(glassesCode)
    }
    const progressState = progressScreen(installSnapshot)
    const screen = progressState === "complete" && autoChainActive ? "finishing" : progressState
    const error: MentraLiveOtaError | null =
      screen === "failed"
        ? {
            code: requiresGlassesReboot ? "bes_restart_required" : "install_failed",
            message: displayedError,
            copyKey,
            glassesCode,
          }
        : null
    const totalSteps = installSnapshot.otaStatus?.totalSteps ?? null
    const artifact = installSnapshot.hotspotArtifact
    const changelogs = screen === "complete" ? releaseChangelogsForActiveChain() : []
    return {
      screen,
      connected: installSnapshot.connected,
      batteryLevel: otaSnapshot.batteryLevel,
      transport: installSnapshot.transport,
      updateRequired: isUpdateRequired,
      versionChange: installSnapshot.isVersionChange,
      versionChangeConverged: installSnapshot.versionChangeConverged,
      versionChangePhase: installSnapshot.versionChangePhase,
      wifiConnected: otaSnapshot.wifiConnected,
      wifiStatusKnown: otaSnapshot.wifiStatusKnown,
      hotspotSupported,
      hotspotPhase: installSnapshot.hotspotPhase,
      hotspotArtifactPercent: installSnapshot.hotspotArtifactPercent,
      hotspotArtifact: artifact ? {kind: artifact.kind, index: artifact.index, totalCount: artifact.totalCount} : null,
      phase: installSnapshot.otaStatus?.phase ?? installSnapshot.otaProgress?.stage ?? null,
      step: installSnapshot.otaStatus?.stepType ?? null,
      currentStep: installSnapshot.otaStatus?.currentStep ?? null,
      totalSteps,
      progress: installProgress(installSnapshot),
      installingApkOnly:
        installSnapshot.otaStatus?.stepType === "apk" &&
        installSnapshot.otaStatus.phase === "install" &&
        totalSteps === 1,
      firmwareRestarting,
      error,
      canInstall: false,
      canRetry: screen === "failed" && !requiresGlassesReboot,
      canFinish: screen === "complete" || (screen === "failed" && requiresGlassesReboot),
      canDismiss: false,
      canDiscard: screen === "disconnected",
      canOpenWifiSetup: screen === "failed" && !hotspotSupported && showChangeWifi,
      continueDisabled: installSnapshot.continueButtonDisabled,
      completedUpdate: false,
      releaseTransition: releaseTransitionFromRange(otaAutoChainReleaseRange()),
      changelogs,
      glassesPackageName: null,
    }
  }, [
    unofficialClientPackage,
    checkState,
    batteryBlocked,
    completedChangelogs,
    completedReleaseTransition,
    completedUpdate,
    errorKind,
    firmwareRestarting,
    installSnapshot,
    isUpdateRequired,
    isVersionChange,
    otaSnapshot,
    offeredReleaseTransition,
    page,
    runtimeReady,
    deviceRevision,
  ])

  return useMemo(
    () => ({state, check, retryCheck: check, install, retryInstall, finish, discard, openWifiSetup}),
    [check, discard, finish, install, openWifiSetup, retryInstall, state],
  )
}