/* eslint-disable react-native/no-raw-text -- BodyText and PercentText are local Text wrappers. */ import React, {useMemo} from "react" import { ActivityIndicator, Platform, Pressable, ScrollView, StyleSheet, Text, View, type StyleProp, type ViewStyle, } from "react-native" import {useMarkdown, type MarkedStyles, type useMarkdownHookOptions} from "react-native-marked" import {SafeAreaView} from "react-native-safe-area-context" import Svg, {Path, Rect} from "react-native-svg" import {OTA_ERROR_ENGLISH_COPY} from "../services/OtaErrorMapping" import { MINIMUM_OTA_BATTERY_LEVEL, useMentraLiveOta, type MentraLiveOtaController, type MentraLiveOtaError, type MentraLiveOtaFlowPage, type MentraLiveOtaState, } from "./useMentraLiveOta" export type {MentraLiveOtaFlowPage} from "./useMentraLiveOta" export type MentraLiveOtaFlowTheme = { background: string border: string error: string foreground: string primary: string primaryText: string textDim: string } export type MentraLiveOtaFlowTranslate = (key: string, options?: Record) => string export type MentraLiveOtaFlowProps = { /** Display name used in update copy. */ deviceName?: string /** Entry page. `progress` exists for recovery/deep-link compatibility. */ initialPage?: MentraLiveOtaFlowPage /** Start the OTA-only projections. Full Engine hosts should pass false. */ initializeRuntime?: boolean /** Called after the final check or when the user leaves an optional update. */ onFinished: () => void /** Host-owned Wi-Fi setup for glasses that do not support hotspot OTA. */ onOpenWifiSetup: () => void /** Lets a host coordinate its global connection overlay with OTA progress and firmware restarts. */ onFirmwareRestartingChange?: (restarting: boolean, progressActive: boolean) => void /** Enables the existing developer-only escape hatches. */ allowDevSkip?: boolean /** Enables the existing super-mode interrupted-session escape hatch. */ superMode?: boolean /** Optional host localization. Defaults to the Mentra App English OTA copy. */ translate?: MentraLiveOtaFlowTranslate /** Optional host theme. Both hosts use the same layout and state machine. */ theme?: Partial style?: StyleProp } const DEFAULT_THEME: MentraLiveOtaFlowTheme = { background: "#FFFFFF", border: "#D7DFDA", error: "#C43131", foreground: "#0E2C1A", primary: "#00B869", primaryText: "#FFFFFF", textDim: "#66736B", } const ENGLISH_COPY: Record = { "ota:downloadingToPhone": "Downloading update to phone…", "ota:startingGlassesHotspot": "Starting glasses hotspot…", "ota:connectingPhoneToGlasses": "Connecting phone to glasses…", "ota:connectingPhoneWifiHint": "Make sure your phone’s Wi-Fi is on.", "ota:startingHotspotUpdate": "Starting update…", "ota:transferringToGlasses": "Transferring update to glasses…", "ota:installingOnGlasses": "Installing update on glasses…", "ota:componentApk": "Glasses software", "ota:componentMtk": "System firmware", "ota:componentBes": "Bluetooth firmware", "ota:updateFile": "File {{current}} of {{total}} · {{component}}", "ota:updatePart": "Update {{current}} of {{total}} · {{component}}", "ota:phoneFileProgress": "Each file downloads separately. Progress is for the current file.", "common:continue": "Continue", "common:done": "Done", "ota:checkingForUpdates": "Checking for updates", "ota:checkingForUpdatesMessage": "Connected devices will perform automatic updates. Automatic updates can be disabled in Device Settings.", "ota:finishingUpdate": "Finishing your update", "ota:checkingAdditionalUpdates": "Checking whether your glasses need any additional updates.", "ota:updateAvailable": "{{deviceName}} Update Available", "ota:batteryRequiredTitle": "Charge {{deviceName}} to Update", "ota:batteryRequiredMessage": "{{deviceName}} is currently at {{batteryLevel}}%. Charge it to at least {{minimumBatteryLevel}}% before updating.", "ota:batteryRequiredLiveUpdate": "This screen will update automatically as the battery charges.", "ota:updateConnectWifi": "Connect your {{deviceName}} to Wi-Fi to install the update.", "ota:wifiRequiredTitle": "Wi-Fi Needed for Update", "ota:updateDescription": "A new update is available for your glasses. We recommend updating now for the best experience.", "ota:updateSequenceMessage": "Your glasses may install more than one update and restart several times. Keep them nearby until finished.", "ota:releaseTransition": "{{fromVersion}} → {{toVersion}}", "ota:releaseTransitionUnknown": "Current version unknown → {{toVersion}}", "ota:updatedToVersion": "Updated to {{version}}", "ota:downgradeAvailable": "{{deviceName}} Version Change Required", "ota:downgradeDescription": "This app requires an earlier glasses software version. Your photos and videos will be preserved, but glasses settings will be reset and restored automatically after the change.", "ota:updateNow": "Update Now", "ota:setupWifi": "Set up Wi-Fi", "ota:updateLater": "Later", "ota:updateComplete": "Update complete", "ota:whatsNew": "What's new", "ota:upToDate": "Up to Date", "ota:devBuild": "Development Build", "ota:devBuildNoOta": "This mobile app is a development build, so automatic glasses updates are disabled. Use the developer settings manifest override to update them manually.", "ota:unofficialClient": "Updates Blocked", "ota:unofficialClientNoOta": "Your glasses are running a sideloaded client, so updates are blocked. Restore the stock client to update them.", "ota:unofficialClientNoOtaNamed": "Your glasses are running a sideloaded client ({{packageName}}), so updates are blocked. Restore the stock client to update them.", "ota:noUpdatesAvailable": "Your glasses are running the latest version.", "ota:checkFailed": "Check Failed", "ota:checkFailedMessage": "Couldn't check for updates. Please check your connection and try again.", "ota:versionInfoFailedMessage": "Couldn't read the glasses software versions. Keep the glasses connected and try again.", "ota:updateInfoUnavailable": "Update Info Unavailable", "ota:updateInfoUnavailableMessage": "Update information for this version of the app is unavailable. Please check the app store for a newer version of the Mentra App.", "ota:downgradeDuration": "Changing versions can take several minutes. Keep your glasses nearby while they install and reconnect.", "ota:versionChangeRestarting": "Installing a different version…", "ota:versionChangeVerifying": "Verifying your glasses…", "ota:versionChangeKeepNearby": "Keep your glasses nearby and connected. They will restart on their own.", "ota:restartingGlasses": "Restarting {{deviceName}}…", "ota:restartingGlassesMessage": "The update is installed. Keep your glasses nearby and leave this screen open while they finish starting.", "ota:restartingGlassesAutomatic": "We'll continue automatically when they're ready.", "ota:versionChangeComplete": "Version Change Complete", "ota:versionChangeCompleteMessage": "Your glasses are now on the required version. Their settings were reset and are being restored automatically.", "ota:versionChangeFirmwarePassComplete": "Firmware updated", "ota:versionChangeFirmwarePassCompleteMessage": "Your glasses restarted with new firmware. One more step: they'll now continue to the required version.", "ota:updateFailed": "Update Failed", ...OTA_ERROR_ENGLISH_COPY, } const componentCopyKey = { apk: "ota:componentApk", mtk: "ota:componentMtk", bes: "ota:componentBes", } as const /** * Copy for the failed screen: the translated copy key when the failure maps to one, * otherwise the engine's English message (phone-side watchdog and preflight text). */ function failureMessage(error: MentraLiveOtaError | null, translate: MentraLiveOtaFlowTranslate): string { if (!error) return translate("ota:errorGeneric") return error.copyKey ? translate(error.copyKey) : error.message } function defaultTranslate(key: string, options?: Record): string { let value = Object.prototype.hasOwnProperty.call(ENGLISH_COPY, key) ? ENGLISH_COPY[key] : key for (const [name, replacement] of Object.entries(options ?? {})) { value = value.replaceAll(`{{${name}}}`, replacement) } return value } export function MentraLiveOtaFlow({ allowDevSkip = typeof __DEV__ !== "undefined" && __DEV__, deviceName = "Mentra Live", initialPage = "check", initializeRuntime = true, onFinished, onFirmwareRestartingChange, onOpenWifiSetup, style, superMode = false, theme, translate = defaultTranslate, }: MentraLiveOtaFlowProps) { const colors = useMemo(() => ({...DEFAULT_THEME, ...theme}), [theme]) const controller = useMentraLiveOta({ initialPage, initializeRuntime, onFinished, onFirmwareRestartingChange, onOpenWifiSetup, }) return } type OtaFlowFrameProps = { allowDevSkip: boolean colors: MentraLiveOtaFlowTheme controller: MentraLiveOtaController deviceName: string style?: StyleProp superMode: boolean translate: MentraLiveOtaFlowTranslate } const previewAction = () => {} /** Renders the real OTA pages without mounting the runtime hook or performing any actions. */ export function MentraLiveOtaPreview({ state, deviceName = "Mentra Live", theme, translate = defaultTranslate, }: Pick & {state: MentraLiveOtaState}) { return ( ) } function OtaFlowFrame({allowDevSkip, colors, controller, deviceName, style, superMode, translate}: OtaFlowFrameProps) { return ( ) } function OtaFlowContent({ allowDevSkip, colors, controller, deviceName, superMode, translate, }: { allowDevSkip: boolean colors: MentraLiveOtaFlowTheme controller: MentraLiveOtaController deviceName: string superMode: boolean translate: MentraLiveOtaFlowTranslate }) { const {state} = controller if (state.screen === "initializing") { return ( ) } if (state.screen === "checking") { return ( {translate("ota:checkingForUpdatesMessage")} ) } if (state.screen === "battery_required") { return ( {state.canDismiss ? ( ) : null} } colors={colors} icon="alert" title={translate("ota:batteryRequiredTitle", {deviceName})}> {translate("ota:batteryRequiredMessage", { batteryLevel: String(state.batteryLevel), deviceName, minimumBatteryLevel: String(MINIMUM_OTA_BATTERY_LEVEL), })} {translate("ota:batteryRequiredLiveUpdate")} ) } if (state.screen === "finishing") { return ( {translate("ota:checkingAdditionalUpdates")} ) } if (state.screen === "update_available" || state.screen === "wifi_required") { const titleKey = state.screen === "wifi_required" ? "ota:wifiRequiredTitle" : state.versionChange ? "ota:downgradeAvailable" : "ota:updateAvailable" return ( {state.canDismiss ? ( ) : null} {allowDevSkip && state.updateRequired ? ( ) : null} }> {state.releaseTransition ? ( {state.releaseTransition.fromVersion ? translate("ota:releaseTransition", { fromVersion: state.releaseTransition.fromVersion, toVersion: state.releaseTransition.toVersion, }) : translate("ota:releaseTransitionUnknown", {toVersion: state.releaseTransition.toVersion})} ) : null} {state.screen === "wifi_required" ? translate("ota:updateConnectWifi", {deviceName}) : translate(state.versionChange ? "ota:downgradeDescription" : "ota:updateDescription")} {translate("ota:updateSequenceMessage")} ) } if (state.screen === "dev_build") { return ( } colors={colors} icon="settings" title={translate("ota:devBuild")}> {translate("ota:devBuildNoOta")} ) } if (state.screen === "unofficial_client") { return ( } colors={colors} icon="settings" title={translate("ota:unofficialClient")}> {state.glassesPackageName ? translate("ota:unofficialClientNoOtaNamed", {packageName: state.glassesPackageName}) : translate("ota:unofficialClientNoOta")} ) } if (state.screen === "up_to_date") { return ( } colors={colors} contentAlignment={state.changelogs.length > 0 ? "top" : "center"} icon="check" title={translate(state.completedUpdate ? "ota:updateComplete" : "ota:upToDate")}> {translate("ota:noUpdatesAvailable")} {state.releaseTransition ? ( {translate("ota:updatedToVersion", {version: state.releaseTransition.toVersion})} ) : null} ) } if (state.screen === "update_info_unavailable") { return ( } colors={colors} icon="alert" title={translate("ota:updateInfoUnavailable")}> {translate("ota:updateInfoUnavailableMessage")} ) } if (state.screen === "check_failed") { return ( {allowDevSkip ? ( ) : null} } colors={colors} icon="alert" title={translate("ota:checkFailed")}> {failureMessage(state.error, translate)} ) } if (state.versionChangePhase === "restarting" || state.versionChangePhase === "verifying") { return ( {translate("ota:versionChangeKeepNearby")} {translate("ota:downgradeDuration")} ) } if (state.screen === "starting" || state.screen === "preparing_hotspot") { const title = translate( state.hotspotPhase === "downloading" ? "ota:downloadingToPhone" : state.hotspotPhase === "starting_hotspot" ? "ota:startingGlassesHotspot" : state.hotspotPhase === "joining_hotspot" ? "ota:connectingPhoneToGlasses" : "ota:startingHotspotUpdate", ) const artifact = state.hotspotPhase === "downloading" ? state.hotspotArtifact : null return ( {artifact ? ( {translate("ota:updateFile", { current: String(artifact.index + 1), total: String(artifact.totalCount), component: translate(componentCopyKey[artifact.kind]), })} ) : null} {state.hotspotPhase === "downloading" && state.hotspotArtifactPercent !== null ? ( ) : null} {state.hotspotPhase === "downloading" ? ( {translate("ota:phoneFileProgress")} ) : null} {/* iOS cannot read the Wi-Fi radio, and a join with Wi-Fi off can wait without failing. */} {state.hotspotPhase === "joining_hotspot" && Platform.OS === "ios" ? ( {translate("ota:connectingPhoneWifiHint")} ) : null} Do not disconnect your glasses. ) } if (state.screen === "updating") { const hotspot = state.transport === "hotspot" const title = hotspot ? translate(state.phase === "download" ? "ota:transferringToGlasses" : "ota:installingOnGlasses") : state.phase === "download" ? "Downloading…" : "Installing…" const component = state.step ? translate(componentCopyKey[state.step]) : null const hasStepCount = state.currentStep !== null && state.totalSteps !== null && state.currentStep > 0 && state.currentStep <= state.totalSteps return ( {hotspot && component ? ( {hasStepCount ? translate("ota:updatePart", { current: String(state.currentStep), total: String(state.totalSteps), component, }) : component} ) : null} {state.installingApkOnly ? ( ) : ( <> )} Do not disconnect your glasses. {state.versionChange && state.phase === "install" ? ( {translate("ota:downgradeDuration")} ) : null} ) } if (state.screen === "restarting") { return ( {translate("ota:restartingGlassesMessage")} {translate("ota:restartingGlassesAutomatic")} ) } if (state.screen === "complete") { const title = state.versionChangeConverged ? translate("ota:versionChangeComplete") : state.versionChange ? translate("ota:versionChangeFirmwarePassComplete") : "Update complete!" const message = state.versionChangeConverged ? translate("ota:versionChangeCompleteMessage") : state.versionChange ? translate("ota:versionChangeFirmwarePassCompleteMessage") : "Your glasses are up to date." return ( } colors={colors} contentAlignment={state.changelogs.length > 0 ? "top" : "center"} icon="check" title={title}> {message} {state.releaseTransition ? ( {translate("ota:updatedToVersion", {version: state.releaseTransition.toVersion})} ) : null} ) } if (state.screen === "failed") { return ( {state.canOpenWifiSetup ? ( ) : null} } colors={colors} icon="alert" title={translate("ota:updateFailed")}> {failureMessage(state.error, translate)} ) } return ( ) : undefined } colors={colors} icon="bluetooth" title="Glasses disconnected"> Reconnecting… ) } type FlowPageProps = { actions?: React.ReactNode children?: React.ReactNode colors: MentraLiveOtaFlowTheme contentAlignment?: "center" | "top" icon: "alert" | "bluetooth" | "check" | "download" | "settings" title: string } function FlowPage({actions, children, colors, contentAlignment = "center", icon, title}: FlowPageProps) { return ( {title} {children} {actions ? {actions} : } ) } function BodyText({children, colors}: {children: React.ReactNode; colors: MentraLiveOtaFlowTheme}) { return {children} } function PercentText({colors, percent}: {colors: MentraLiveOtaFlowTheme; percent: number}) { return {Math.round(percent)}% } function ChangelogMarkdown({colors, markdown}: {colors: MentraLiveOtaFlowTheme; markdown: string}) { const markdownStyles = useMemo( () => ({ blockquote: { borderLeftColor: colors.primary, borderLeftWidth: 3, marginVertical: 2, opacity: 1, paddingLeft: 12, }, code: { backgroundColor: colors.background, borderColor: colors.border, borderRadius: 8, borderWidth: 1, padding: 12, }, codespan: { backgroundColor: colors.border, color: colors.foreground, fontFamily: "monospace", fontSize: 13, fontStyle: "normal", fontWeight: "400", }, em: {color: colors.textDim, fontSize: 14, lineHeight: 20}, h1: { borderBottomWidth: 0, color: colors.foreground, fontSize: 18, fontWeight: "700", lineHeight: 24, marginVertical: 0, paddingBottom: 0, }, h2: { borderBottomWidth: 0, color: colors.foreground, fontSize: 17, fontWeight: "700", lineHeight: 23, marginVertical: 0, paddingBottom: 0, }, h3: {color: colors.foreground, fontSize: 16, fontWeight: "700", lineHeight: 22, marginVertical: 0}, h4: {color: colors.foreground, fontSize: 15, fontWeight: "700", lineHeight: 21, marginVertical: 0}, h5: {color: colors.foreground, fontSize: 14, fontWeight: "700", lineHeight: 20, marginVertical: 0}, h6: {color: colors.textDim, fontSize: 14, fontWeight: "600", lineHeight: 20, marginVertical: 0}, hr: {borderBottomColor: colors.border, marginVertical: 2}, image: {borderRadius: 8}, li: {color: colors.textDim, fontSize: 14, lineHeight: 20}, link: { color: colors.primary, fontSize: 14, fontStyle: "normal", lineHeight: 20, textDecorationLine: "underline", }, paragraph: {paddingVertical: 0}, strikethrough: {color: colors.textDim, fontSize: 14, lineHeight: 20}, strong: {color: colors.foreground, fontSize: 14, fontWeight: "700", lineHeight: 20}, table: {borderColor: colors.border, borderRadius: 8}, tableCell: {padding: 8}, text: {color: colors.textDim, fontSize: 14, lineHeight: 20}, }), [colors], ) const markdownTheme = useMemo>( () => ({ colors: { background: colors.background, border: colors.border, code: colors.border, link: colors.primary, text: colors.textDim, }, }), [colors], ) const elements = useMarkdown(markdown, {colorScheme: "light", styles: markdownStyles, theme: markdownTheme}) return ( {elements} ) } export function ChangelogList({ changelogs, colors, title, }: { changelogs: MentraLiveOtaController["state"]["changelogs"] colors: MentraLiveOtaFlowTheme title: string }) { if (changelogs.length === 0) return null return ( {title} {changelogs.map((entry, index) => ( 0 && styles.changelogEntryDivider, index > 0 && {borderTopColor: colors.border}, ]}> {entry.version} ))} ) } function FlowButton({ colors, disabled = false, label, onPress, secondary = false, }: { colors: MentraLiveOtaFlowTheme disabled?: boolean label: string onPress: () => void secondary?: boolean }) { return ( [ styles.button, { backgroundColor: secondary ? colors.background : colors.foreground, borderColor: secondary ? colors.border : colors.foreground, opacity: disabled ? 0.45 : pressed ? 0.75 : 1, }, ]} testID={`button-${label}`}> {label} ) } function MentraMark({color}: {color: string}) { return ( ) } function FlowIcon({colors, name}: {colors: MentraLiveOtaFlowTheme; name: FlowPageProps["icon"]}) { const color = name === "alert" || name === "bluetooth" ? colors.error : colors.primary if (name === "download" || name === "check") { // Lucide arrow-down-to-line and check; see ./lucide-LICENSE.txt. return ( {name === "download" ? ( <> ) : ( )} ) } const glyph = name === "alert" ? "!" : name === "settings" ? "⚙" : "⌁" return {glyph} } const styles = StyleSheet.create({ safeArea: {flex: 1}, header: { alignItems: "center", flexDirection: "row", height: 48, justifyContent: "space-between", paddingHorizontal: 20, }, page: {flex: 1, paddingBottom: 24, paddingHorizontal: 24}, contentScroll: {flex: 1}, centerContent: {alignItems: "center", flexGrow: 1, gap: 16, justifyContent: "center"}, topContent: {justifyContent: "flex-start", paddingBottom: 16, paddingTop: 12}, actionSpacer: {height: 48}, actions: {gap: 12}, icon: {fontSize: 64, fontWeight: "500", lineHeight: 72, textAlign: "center"}, svgIcon: {alignItems: "center", height: 72, justifyContent: "center", width: 72}, title: {fontSize: 20, fontWeight: "600", textAlign: "center"}, body: {fontSize: 14, lineHeight: 20, maxWidth: 420, textAlign: "center"}, percent: {fontSize: 30, fontVariant: ["tabular-nums"], fontWeight: "700"}, progressTrack: {borderRadius: 4, height: 8, maxWidth: 420, overflow: "hidden", width: "100%"}, progressFill: {borderRadius: 4, height: 8}, changelogCard: { borderRadius: 16, borderWidth: 1, flexGrow: 1, gap: 12, maxWidth: 420, minHeight: 200, padding: 16, width: "100%", }, changelogTitle: {fontSize: 16, fontWeight: "700"}, // Bound the notes themselves so the card can grow for its title, but not for all of the Markdown. changelogList: {flexGrow: 1, height: 120, width: "100%"}, changelogContent: {gap: 20, paddingBottom: 4}, changelogEntry: {gap: 8}, changelogEntryDivider: {borderTopWidth: StyleSheet.hairlineWidth, paddingTop: 20}, changelogVersion: {fontSize: 14, fontWeight: "600"}, changelogMarkdownContent: {gap: 10}, button: { alignItems: "center", borderRadius: 50, borderWidth: 1, justifyContent: "center", minHeight: 44, paddingHorizontal: 20, }, buttonText: {fontSize: 14, fontWeight: "500"}, })