MentraOS / mobile /modules /engine /src /react /useMentraLiveOta.ts
Anirudh1950's picture
Add files using upload-large-folder tool
8a29801 verified
Raw History Blame Contribute Delete
35.9 kB
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],
)
}