diff --git a/apps/mobile/src/modules/debug/index.tsx b/apps/mobile/src/modules/debug/index.tsx
index 38c9f48cd..57f84ca14 100644
--- a/apps/mobile/src/modules/debug/index.tsx
+++ b/apps/mobile/src/modules/debug/index.tsx
@@ -14,6 +14,8 @@ import { BugCuteReIcon } from "@/src/icons/bug_cute_re"
import { JotaiPersistSyncStorage } from "@/src/lib/jotai"
import { Navigation } from "@/src/lib/navigation/Navigation"
import { setEnvProfile, useEnvProfile } from "@/src/lib/proxy-env"
+import { toast } from "@/src/lib/toast"
+import { useOtaActions, useOtaState } from "@/src/modules/ota/provider"
import { DebugScreen } from "@/src/screens/(headless)/DebugScreen"
export const DebugButton = () => {
@@ -91,7 +93,32 @@ export const DebugButton = () => {
}
export const EnvProfileIndicator = () => {
const envProfile = useEnvProfile()
+ const otaState = useOtaState()
+ const { checkForUpdates, reloadUpdate } = useOtaActions()
if (!__DEV__ && envProfile === "prod") return null
+
+ const handleCheckOtaUpdate = async () => {
+ try {
+ const result = await checkForUpdates()
+ if (result.kind === "available") {
+ toast.success(`OTA update ${result.version} is ready`)
+ return
+ }
+
+ toast.info("No OTA update available")
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Failed to check OTA update")
+ }
+ }
+
+ const handleReloadOtaUpdate = async () => {
+ try {
+ await reloadUpdate()
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Failed to reload OTA update")
+ }
+ }
+
return (
{
)
})}
+ {
+ void handleCheckOtaUpdate()
+ }}
+ >
+ Check OTA Update
+
+ {
+ void handleReloadOtaUpdate()
+ }}
+ >
+
+ {otaState.pendingVersion
+ ? `Reload OTA Update (${otaState.pendingVersion})`
+ : "Reload OTA Update"}
+
+
diff --git a/apps/mobile/src/modules/ota/__tests__/client.test.ts b/apps/mobile/src/modules/ota/__tests__/client.test.ts
new file mode 100644
index 000000000..9908bdc6e
--- /dev/null
+++ b/apps/mobile/src/modules/ota/__tests__/client.test.ts
@@ -0,0 +1,53 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+import { fetchStorePolicy } from "../client"
+
+describe("fetchStorePolicy", () => {
+ beforeEach(() => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({ action: "block", targetVersion: "0.4.3", message: "Update required" }),
+ {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ },
+ ),
+ ),
+ )
+ })
+
+ it("returns the parsed policy response", async () => {
+ const result = await fetchStorePolicy({
+ baseUrl: "https://ota.folo.is",
+ product: "mobile",
+ channel: "production",
+ installedBinaryVersion: "0.4.1",
+ })
+
+ expect(result.action).toBe("block")
+ expect(result.targetVersion).toBe("0.4.3")
+ })
+
+ it("throws when the policy request fails", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ message: "Internal Server Error" }), {
+ status: 500,
+ headers: { "content-type": "application/json" },
+ }),
+ ),
+ )
+
+ await expect(
+ fetchStorePolicy({
+ baseUrl: "https://ota.folo.is",
+ product: "mobile",
+ channel: "production",
+ installedBinaryVersion: "0.4.1",
+ }),
+ ).rejects.toThrow("Failed to fetch OTA policy")
+ })
+})
diff --git a/apps/mobile/src/modules/ota/client.ts b/apps/mobile/src/modules/ota/client.ts
new file mode 100644
index 000000000..7ef0f2364
--- /dev/null
+++ b/apps/mobile/src/modules/ota/client.ts
@@ -0,0 +1,31 @@
+export interface FetchStorePolicyInput {
+ baseUrl: string
+ product: string
+ channel: string
+ installedBinaryVersion: string
+}
+
+export interface StorePolicyResponse {
+ action: string
+ targetVersion?: string | null
+ message?: string | null
+}
+
+export const fetchStorePolicy = async ({
+ baseUrl,
+ product,
+ channel,
+ installedBinaryVersion,
+}: FetchStorePolicyInput): Promise => {
+ const requestUrl = new URL("/policy", baseUrl)
+ requestUrl.searchParams.set("product", product)
+ requestUrl.searchParams.set("channel", channel)
+ requestUrl.searchParams.set("installedBinaryVersion", installedBinaryVersion)
+
+ const response = await fetch(requestUrl.toString())
+ if (!response.ok) {
+ throw new Error(`Failed to fetch OTA policy (${response.status})`)
+ }
+
+ return (await response.json()) as StorePolicyResponse
+}
diff --git a/apps/mobile/src/modules/ota/provider.tsx b/apps/mobile/src/modules/ota/provider.tsx
index 92ae2d7d2..ecf4b9486 100644
--- a/apps/mobile/src/modules/ota/provider.tsx
+++ b/apps/mobile/src/modules/ota/provider.tsx
@@ -1,13 +1,29 @@
+import { nativeApplicationVersion } from "expo-application"
import type { Manifest } from "expo-updates"
import * as Updates from "expo-updates"
-import type { PropsWithChildren } from "react"
+import type { ActionDispatch, PropsWithChildren } from "react"
import { createContext, use, useEffect, useMemo, useReducer } from "react"
import { InteractionManager } from "react-native"
+import { fetchStorePolicy } from "./client"
import { initialOtaState, reduceOtaState } from "./store"
-import type { OtaState } from "./types"
+import type { OtaAction, OtaState } from "./types"
const OtaContext = createContext(initialOtaState)
+const OtaBaseUrl = "https://ota.folo.is"
+const OtaProduct = "mobile"
+
+export type OtaCheckForUpdatesResult = { kind: "available"; version: string } | { kind: "idle" }
+
+interface OtaActions {
+ checkForUpdates: () => Promise
+ reloadUpdate: () => Promise
+}
+
+const OtaActionsContext = createContext({
+ checkForUpdates: async () => ({ kind: "idle" }),
+ reloadUpdate: async () => {},
+})
const resolvePendingVersion = (manifest: Manifest | undefined): string => {
if (!manifest) {
@@ -30,6 +46,112 @@ const resolvePendingVersion = (manifest: Manifest | undefined): string => {
return Updates.runtimeVersion ?? "unknown"
}
+const getOtaChannel = () => Updates.channel ?? "default"
+
+const getInstalledBinaryVersion = () =>
+ nativeApplicationVersion ?? Updates.runtimeVersion ?? "unknown"
+
+const getErrorMessage = (error: unknown, fallback: string) => {
+ return error instanceof Error ? error.message : fallback
+}
+
+const refreshStorePolicy = async () => {
+ try {
+ return await fetchStorePolicy({
+ baseUrl: OtaBaseUrl,
+ product: OtaProduct,
+ channel: getOtaChannel(),
+ installedBinaryVersion: getInstalledBinaryVersion(),
+ })
+ } catch (error) {
+ console.warn("[ota] Failed to fetch store policy", error)
+ return null
+ }
+}
+
+const runOtaCheck = async ({
+ dispatch,
+ currentPendingVersion,
+ isUpdatePending,
+ shouldCancel = () => false,
+}: {
+ dispatch: ActionDispatch<[action: OtaAction]>
+ currentPendingVersion: string | null
+ isUpdatePending: boolean
+ shouldCancel?: () => boolean
+}): Promise => {
+ const dispatchIfActive = (action: OtaAction) => {
+ if (!shouldCancel()) {
+ dispatch(action)
+ }
+ }
+
+ const policyPromise = refreshStorePolicy()
+
+ try {
+ if (currentPendingVersion) {
+ await policyPromise
+ if (shouldCancel()) {
+ return { kind: "idle" }
+ }
+
+ dispatchIfActive({
+ type: "downloaded",
+ version: currentPendingVersion,
+ })
+ return { kind: "available", version: currentPendingVersion }
+ }
+
+ dispatchIfActive({ type: "checking" })
+
+ const checkResult = await Updates.checkForUpdateAsync()
+ if (shouldCancel()) {
+ return { kind: "idle" }
+ }
+
+ if (!checkResult.isAvailable) {
+ await policyPromise
+ if (!isUpdatePending) {
+ dispatchIfActive({ type: "reset" })
+ }
+ return { kind: "idle" }
+ }
+
+ dispatchIfActive({ type: "downloading" })
+
+ const fetchResult = await Updates.fetchUpdateAsync()
+ if (shouldCancel()) {
+ return { kind: "idle" }
+ }
+
+ await policyPromise
+
+ if (fetchResult.isNew && fetchResult.manifest) {
+ const version = resolvePendingVersion(fetchResult.manifest)
+ dispatchIfActive({
+ type: "downloaded",
+ version,
+ })
+ return { kind: "available", version }
+ }
+
+ if (!isUpdatePending) {
+ dispatchIfActive({ type: "reset" })
+ }
+
+ return { kind: "idle" }
+ } catch (error) {
+ await policyPromise
+
+ dispatchIfActive({
+ type: "failed",
+ message: getErrorMessage(error, "Failed to check for updates."),
+ })
+
+ throw error instanceof Error ? error : new Error("Failed to check for updates.")
+ }
+}
+
export const OtaProvider = ({ children }: PropsWithChildren) => {
const { checkError, downloadError, downloadedUpdate, isUpdatePending } = Updates.useUpdates()
const [state, dispatch] = useReducer(reduceOtaState, initialOtaState)
@@ -42,6 +164,8 @@ export const OtaProvider = ({ children }: PropsWithChildren) => {
return resolvePendingVersion(downloadedUpdate.manifest)
}, [downloadedUpdate, isUpdatePending])
+ const currentPendingVersion = nativePendingVersion ?? state.pendingVersion
+
useEffect(() => {
if (!nativePendingVersion) {
return
@@ -74,46 +198,14 @@ export const OtaProvider = ({ children }: PropsWithChildren) => {
const runBackgroundCheck = async () => {
try {
- dispatch({ type: "checking" })
-
- const checkResult = await Updates.checkForUpdateAsync()
- if (isCancelled) {
- return
- }
-
- if (!checkResult.isAvailable) {
- if (!isUpdatePending) {
- dispatch({ type: "reset" })
- }
- return
- }
-
- dispatch({ type: "downloading" })
- const fetchResult = await Updates.fetchUpdateAsync()
- if (isCancelled) {
- return
- }
-
- if (fetchResult.isNew && fetchResult.manifest) {
- dispatch({
- type: "downloaded",
- version: resolvePendingVersion(fetchResult.manifest),
- })
- return
- }
-
- if (!isUpdatePending) {
- dispatch({ type: "reset" })
- }
- } catch (error) {
- if (isCancelled) {
- return
- }
-
- dispatch({
- type: "failed",
- message: error instanceof Error ? error.message : "Failed to check for updates.",
+ await runOtaCheck({
+ dispatch,
+ currentPendingVersion: nativePendingVersion,
+ isUpdatePending,
+ shouldCancel: () => isCancelled,
})
+ } catch {
+ // runOtaCheck already syncs OTA failures into state.
}
}
@@ -127,19 +219,51 @@ export const OtaProvider = ({ children }: PropsWithChildren) => {
}
}, [isUpdatePending, nativePendingVersion])
+ const actions = useMemo(() => {
+ return {
+ checkForUpdates: async () => {
+ if (!Updates.isEnabled) {
+ throw new Error("OTA updates are not enabled.")
+ }
+
+ return runOtaCheck({
+ dispatch,
+ currentPendingVersion,
+ isUpdatePending,
+ })
+ },
+ reloadUpdate: async () => {
+ if (!Updates.isEnabled) {
+ throw new Error("OTA updates are not enabled.")
+ }
+
+ if (!currentPendingVersion) {
+ throw new Error("No OTA update is ready to reload.")
+ }
+
+ await Updates.reloadAsync()
+ },
+ }
+ }, [currentPendingVersion, isUpdatePending])
+
const value = useMemo(() => {
- if (!nativePendingVersion) {
+ if (!currentPendingVersion) {
return state
}
return {
status: "ready" as const,
- pendingVersion: nativePendingVersion,
+ pendingVersion: currentPendingVersion,
errorMessage: null,
}
- }, [nativePendingVersion, state])
+ }, [currentPendingVersion, state])
- return {children}
+ return (
+
+ {children}
+
+ )
}
export const useOtaState = () => use(OtaContext)
+export const useOtaActions = () => use(OtaActionsContext)